Divya Jose
Divya Jose

Reputation: 389

HFFSWorkBook download(Apache POI) + servlet response

I want to download an .xls file with content in it. This is the method that I have written to process the .xls file according to my requirements and then download it.

 public static void readDataFromResponse(String csvData, String fileName,
    HttpServletResponse response) throws IOException{
    if(!csvData.isEmpty()){
        BufferedReader br = null;
        byte[] binaryData = csvData.getBytes(Charset.forName("UTF-8"));
        HSSFWorkbook workBook = new HSSFWorkbook();
        HSSFSheet sheet = workBook.createSheet(fileName);
          // do something to insert values into excel.
        }

        response.setHeader("Content-Length", "" + Integer.toString(binaryData.length));
        response.setContentType("application/ms-excel");
        response.addHeader("Content-Disposition",String.join("","attachment; filename=" + fileName + ".xls"));
        response.addHeader("Cache-Control", "public, must-revalidate, post-check=0, pre-check=0");

       //XLS file is downloaded but it is in binary. Not human readable
        OutputStream outputStream = response.getOutputStream();
        workBook.write(outputStream);
        outputStream.flush();
    }

With this code the excel is exported however the content is not readable.I get the binary representation of the workbook. How to export Excel with data that is readable?

Upvotes: 1

Views: 2176

Answers (1)

Rohit Yadav
Rohit Yadav

Reputation: 2568

You need set the proper values of HttpResponse object

Example

For .Xls file

response.setHeader("Content-Type", application/vnd.ms-excel);
response.setCharacterEncoding("UTF-8");

For Excel2007 and above .xlsx files

response.setCharacterEncoding("UTF-8");    
response.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

Upvotes: 2

Related Questions