Home > Net >  Excel file exported to ServletOutputStream is corrupted
Excel file exported to ServletOutputStream is corrupted

Time:12-06

I am writing an excel file onto ServletOutputStream (using HSSFWorkBook for xls and XSSFWorkBook for xlsx). The excel that gets downloaded as part of the ServletResponse is corrupted and contains junk characters.

  outStream = response.getOutputStream(); //ServletOutputStream outStream
  workbook.write(outStream); //HSSFWorkBook/XSSFWorkBook
  workbook.close();
  outStream.flush();

I have tried writing the excel file onto FileOutputStream and it works fine. The excel file is readable and intact.

Had checked several other StackOverflow queries on the same issue. Had tried changing the Content Type of servlet response to "application/excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/vnd.ms-excel" etc. But the issue still persists.

However, I need to write the excel to ServletOutputStream (aware of the binary nature of the servlet output stream and had also tried writing excel to ByteOutputStream and then writing from the derived ByteOuputArray to ServletOutputStream).

Please help.

PS: This code has been done from both JSP and Java Servlet class. Both produce the same outcome.

CodePudding user response:

Thanks a lot BalusC!

I've reset the HttpServletResponse object as suggested and then set the header and wrote the excel to the ServletOutputStream.

response.reset()

The excel downloaded perfectly!

  • Related