java - Excel 无法以正确的格式导出

标签 java excel

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

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

最佳答案

检查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();
}

关于java - Excel 无法以正确的格式导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24348674/

相关文章:

java - Selenium Jenkins Linux TestNG - 如何运行?

JAVA,NodeSet转换为XML,解析将其插入树中

excel - 如何为一张索引表中的每个工作表创建一个超链接?

存在时的 VBA 数据透视表过滤器

Excel:基于一列值和另一列类别创建列

java - 无法将枚举列表传递到 Hibernate 查询中?

java - EasyMock问题,调用实例上的方法但对如何获取该实例不感兴趣

java - SAP Java 连接器存在问题

c# - NPOI Excel 数字格式未显示在 asp.net 的 Excel 工作表中

vba - Excel VBA - 如果单元格为空输入内容,否则返回错误