【发布时间】:2015-03-23 05:37:05
【问题描述】:
我正在使用Apache POI 在我的 spring mvc 应用程序中生成 excel 文件。这是我的春季行动:
@RequestMapping(value = "/excel", method = RequestMethod.POST)
public void companyExcelExport(@RequestParam String filter, @RequestParam String colNames, HttpServletResponse response) throws IOException{
XSSFWorkbook workbook = new XSSFWorkbook();
//code for generate excel file
//....
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=test.xlsx");
workbook.write(response.getOutputStream());
response.setHeader("Content-Length", "" + /* How can i access workbook size here*/);
}
我使用了XSSFWorkbook,因为我需要生成 Excel 2007 格式。但我的问题是XSSFWorkbook 没有getBytes 或getSize 方法。如何计算生成的 xlsx 文件的大小?
编辑:我在这里使用了ByteArrayOutputStream:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
workbook.write(response.getOutputStream());
workbook.write(byteArrayOutputStream);
response.setHeader("Content-Length", "" + byteArrayOutputStream.size());
【问题讨论】:
-
将工作簿写入 ByteArrayOutputStream,从中获取大小,然后将字节写入真实流?
-
我尝试了您的解决方案,但浏览器仍然不显示文件大小。
-
请更新问题,说明您如何使用 ByteArrayOutputStream
-
在写响应之前设置标题。并使用setContentLength()进行设置。
标签: java spring-mvc servlets apache-poi export-to-excel