java - 使用 POI 从 .xls 升级到 .xlsx

标签 java excel apache-poi

我有一个网络应用程序,其中有 excel 文件 (.xls) 下载选项。现在我必须在 .xlsx 中提供该功能

我正在尝试使用 POI Jar。当我尝试将其作为一个独立的应用程序时,它工作正常,但是当我尝试将其集成到 Web 应用程序中时,出现错误

Excel Found Unreadable Content in FILENAME.xlsx. do you want to recover the content of this workbook?
If you trust the source of this workbook click yes!

XSSFWorkbook w = FileName.createExcelWorkbookPosition(
        request.getParameter("BSNS_DT"));
response.setContentType(
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition","attachment;filename=filename.xlsx");
w.write(response.getOutputStream());

这是我创建电子表格的 Java 代码:

public static XSSFWorkbook createExcelWorkbookPosition(String BsnsDate)
    throws Exception
{
    FileOutputStream out = new FileOutputStream("workbook.xlsx");

    // create a new workbook
    XSSFWorkbook wb = new XSSFWorkbook();
    // create a new sheet
    XSSFSheet s = wb.createSheet();
    // declare a row object reference
    XSSFRow r = null;
    // declare a cell object reference
    XSSFCell c = null;

    // header row and columns
    r = s.createRow(0);
    c = r.createCell(0);
    c.setCellValue("Business Date");    
    //c.setCellStyle(cs);
    c = r.createCell(1);
    c.setCellValue("Account No");

    try {
        wb.write(out);
        out.close();
        System.out.println("File writed");
    } catch (Exception e) {
        System.out.println("Error");
        System.out.println(e);
    }
    return wb;
}

有人可以帮忙吗?对不起任何糟糕的英语!谢谢。

最佳答案

我有一个非常相似的问题,请查看 Forcing the browser to download a docx file in JAVA generates a corrupted document .重点是添加响应的 Content-Length header 。

尝试让 createExcelWorkbookPosition 返回文件而不是 XSSFWorkbook:

public static File createExcelWorkbookPosition(String BsnsDate) throws Exception {  
    File file = new File("workbook.xlsx");
    FileOutputStream out = new FileOutputStream(file);
    // ...  
    return file;
}

然后:

File file = FileName.createExcelWorkbookPosition(request.getParameter("BSNS_DT"));
// ...
response.setContentLength((int) file.length());    

InputStream in = new FileInputStream(file);
OutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
    out.write(buffer, 0, len);
}
// if using Apache IO, the above code can be simplified to IOUtils.copy(in, out);
// if using Guava, Files.copy(file, out);

// don't forget to close your streams and flush the response buffer

关于java - 使用 POI 从 .xls 升级到 .xlsx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23339098/

相关文章:

java - 如何使用 Apache POI-HSMF 从 Outlook 消息文件中检索内容类型和内容处置?

java - 在 JPA 中获取单列值

java - Spring Boot 中的同步事务

java - 声明类对象的正确方法是什么?

vba - Excel oleobject 无法删除

java - Apache POI下载后初始计算公式

java - 在运行时,查找 Java 应用程序中扩展基类的所有类

Excel IF 条件,如果作为数组公式输入,则计算结果为 TRUE,否则为 FALSE

vba - 换工作表时如何让Excel选择同一个单元格?

java - 如何使用 Apache POI 为 .xlsx 文件中的所有单元格将空白返回为 null?