使用POI从.xls升级到.xlsx

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

我正在尝试使用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()); 

以下是我创build电子表格的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; } 

任何人都可以请帮忙? 对不起,英文不好! 谢谢。

我有一个相当类似的问题,请看看在强制浏览器下载一个docx文件在JAVA生成一个损坏的文件 。 重点是添加响应的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