使用POI从.xls升级到.xlsx

时间:2014-04-28 10:48:54

标签: java excel apache-poi

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

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

  

Excel在FILENAME.xlsx中找到了不可读的内容。你想恢复这本工作簿的内容吗?   如果您信任此工作簿的来源,请单击“是”!

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;
}

有人可以帮忙吗?对不起,英语不好!感谢。

1 个答案:

答案 0 :(得分:4)

我有一个非常相似的问题,请看Forcing the browser to download a docx file in JAVA generates a corrupted document。关键是要添加响应的Content-Length标头。

尝试让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