Excel没有以适当的格式导出

时间:2014-06-22 06:21:28

标签: java excel

我正在尝试使用jsp将数据导出到excel。但它没有以excel格式正确导出,整个html页面刚刚导出。我不知道如何使用Apache POI的任何东西。我使用下面的代码

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

1 个答案:

答案 0 :(得分:0)

检查this教程


您需要使用POI库,然后您可以通过简单的代码将任何数据写入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();
}