2014-06-22 71 views
1

我想用jsp將數據導出到excel。但它沒有以excel格式正確導出,整個html頁面正在導出。我不知道如何使用任何關於Apache POI的東西。我使用下面的代碼Excel沒有得到正確的格式導出

response.setHeader("Content-Disposition", "attachment;filename=name.xls"); 
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet); 

回答

0

檢查this教程


您需要使用POI Libary,然後你可以寫任何數據通過簡單的代碼到excel文件,像這樣:

//Blank workbook 
XSSFWorkbook workbook = new XSSFWorkbook(); 

//Create a blank sheet 
XSSFSheet sheet = workbook.createSheet("Employee Data"); 

//This data needs to be written (Object[]) 
Map<String, Object[]> data = new TreeMap<String, Object[]>(); 
data.put("1", new Object[] {"ID", "NAME", "LASTNAME"}); 
data.put("2", new Object[] {1, "Amit", "Shukla"}); 
data.put("3", new Object[] {2, "Lokesh", "Gupta"}); 
data.put("4", new Object[] {3, "John", "Adwards"}); 
data.put("5", new Object[] {4, "Brian", "Schultz"}); 

//Iterate over data and write to sheet 
Set<String> keyset = data.keySet(); 
int rownum = 0; 
for (String key : keyset) 
{ 
    Row row = sheet.createRow(rownum++); 
    Object [] objArr = data.get(key); 
    int cellnum = 0; 
    for (Object obj : objArr) 
    { 
     Cell cell = row.createCell(cellnum++); 
     if(obj instanceof String) 
      cell.setCellValue((String)obj); 
     else if(obj instanceof Integer) 
      cell.setCellValue((Integer)obj); 
    } 
} 
try 
{ 
    //Write the workbook in file system 
    FileOutputStream out = new FileOutputStream(new File("howtodoinjava_demo.xlsx")); 
    workbook.write(out); 
    out.close(); 
    System.out.println("howtodoinjava_demo.xlsx written successfully on disk."); 
} 
catch (Exception e) 
{ 
    e.printStackTrace(); 
} 
相關問題