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没有getBytesgetSize方法。如何计算生成的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());

希望能有所帮助。