Home » excel » java – write XSSFWorkbook excel file to response stream

java – write XSSFWorkbook excel file to response stream

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have this webpage
when button clicked, it reads data and saves file to location xyz.

i dont want that. i want it down load via the chrome browser.

how do i send the response below?

The line giving error is response.getOutputStream().write(outputStream);

Thanks

public void exportCOAExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {

    //works well. save excel file to desktop
    XSSFWorkbook workbook = new XSSFWorkbook ();
    FileOutputStream outputStream = new FileOutputStream("C:\Users\user\Desktop\revenue.xls");
    workbook.write(outputStream);
    outputStream.flush();
    outputStream.close();

   //trying to get browser to download the file
    response.setContentType("text/xls");
    response.setHeader("Content-disposition", "attachment;filename=" + "a.xls");

   /************problematic line************/
   response.getOutputStream().write(outputStream);

    response.getOutputStream().flush();

}
How to&Answers:

You can write the workbook directly to the response’s outputstream.

XSSFWorkbook workbook = new XSSFWorkbook();
response.setContentType("text/xls");
response.setHeader("Content-disposition", "attachment;filename=" + "a.xls");

try (OutputStream outputStream = response.getOutputStream()) {
     workbook.write(outputStream);
}