6

I'm using Apache POI for generating 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 XSSFWorkbook because i need to generate Excel 2007 format. but my problem is XSSFWorkbook does not have getBytes or getSize method. How can i calculate size of generated xlsx file?

EDIT: I used ByteArrayOutputStream like here:

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
workbook.write(response.getOutputStream()); 
workbook.write(byteArrayOutputStream);
response.setHeader("Content-Length", "" + byteArrayOutputStream.size());
hamed
  • 7,939
  • 15
  • 60
  • 114
  • Write the Workbook into a ByteArrayOutputStream, get the size from that, then write the bytes to the real stream? – Gagravarr Jan 24 '15 at 07:29
  • I tried your solution, but still browser does not show file size. – hamed Jan 24 '15 at 08:30
  • please update the question , with how you used the ByteArrayOutputStream –  Jan 24 '15 at 08:44
  • 2
    set the header **before** writing the response. And use [setContentLength()](http://docs.oracle.com/javaee/6/api/javax/servlet/ServletResponse.html#setContentLength%28int%29) to set it. – JB Nizet Jan 24 '15 at 08:53

1 Answers1

4

As @JB Nizet said : set the Header before writing the response .

so what you should do is the following :

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

and please refer to this answer here , as it describes how to use the ByteArrayOutputStream with the HSSFWorkbook .

Hope that helps .

Community
  • 1
  • 1
  • 3
    Ok, this worked. thanks. But is there anyway to do that without ByteArrayOutputStream and with the XSSFWorkbook ? – hamed Jan 24 '15 at 09:32