Apache POI - get the size of the generated excel file

I am using Apache POI to create an excel file in my spring mvc application. here is my spring action:

 @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*/);
}

I used XSSFWorkbookbecause I need to create an Excel 2007 format. But my problem XSSFWorkbookhas no method getBytesor getSize. How can I calculate the size of the generated xlsx file?

EDIT: I used ByteArrayOutputStreamas here:

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
workbook.write(response.getOutputStream()); 
workbook.write(byteArrayOutputStream);
response.setHeader("Content-Length", "" + byteArrayOutputStream.size());
+4
source share
1 answer

As @JB Nizet said: set the title before writing the answer.

so you should do the following:

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
workbook.write(byteArrayOutputStream);
response.setHeader("Content-Length", "" + byteArrayOutputStream.size());
workbook.write(response.getOutputStream()); 

, , ByteArrayOutputStream HSSFWorkbook.

, .

+3

All Articles