I created a word document using Apache POI API and can write the file to my local machine and it works very well but when writing to response.getOutputStream() to be able to allow the user to download using the browser, the word document gets corrupted.
Here's my code:
String docFile = "inv_export_012.docx";
FileOutputStream fos= new FileOutputStream("C:\\temp\\" + docFile);
//set response headers
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
response.setHeader("Content-Disposition","attachment; filename=" + docFile);
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
//create docx format using XWPFDocument
XWPFDocument wordDocument = new XWPFDocument();
XWPFParagraph p1 = wordDocument.createParagraph();
p1.setAlignment(ParagraphAlignment.LEFT);
XWPFRun r1 = p1.createRun();
r1.setText("Invoice Number: 00000000XXX");
r1.addCarriageReturn();
//write document to local C: drive
//this step works well and I can successfully create the document
wordDocument.write(fos);
//set content length
response.setHeader("Content-Length", String.valueOf(new File("C:\\temp\\" + docFile).length()));
fos.close();
wordDocument.write(response.getOutputStream());
Also tried the binary formats and it doesn't work either.
response.setContentType("application/octet-stream");
- Java version: 1.6 (Can't update to new version yet)
- Apache POI: 3.16
- Browser: Internet Explorer 11 (My application is only certified in IE so can't use other browsers)
- Office 2013
It works well and document is created successfully on my local desktop. If I try to download using the browser and open it directly (or save it and open it), below error appears indicating document is corrupt. Clicking to open the document still opens the document but anyone knows why I am getting this message? Any help would be appreciated!!
Clicking OK I get this message:
If I Click 'Yes' it does open the document.
EDIT: 06/29- Updated the code to generate *.docx format. Also added Content-Length in the response header. Tried by removing the Content-Length too both of which didn't work.


Found out that POI 3.16 has this problem, this issue is resolved when I upgraded to Apache POI 4.0.0 jar.