apache POI-获取生成的Excel文件的大小
我正在使用Apache POI在Spring MVC应用程序中生成Excel文件。这是我的spring动作:
@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());
回答:
正如@JB Nizet所说:在编写响应之前设置Header。
因此,您应该执行以下操作:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();workbook.write(byteArrayOutputStream);
response.setHeader("Content-Length", "" + byteArrayOutputStream.size());
workbook.write(response.getOutputStream());
希望能有所帮助。
以上是 apache POI-获取生成的Excel文件的大小 的全部内容, 来源链接: utcz.com/qa/431164.html