0

I have generated the Excel report using Apache POI. What I want now, I want to send this to the browser for download. My JSP is as follows.

<html>
  <head><title> Excel Generator</title>
    </head>
  <body>
    <a href="../houseHoldReportGenCtr">generate report</a>
  </body>
</html>

Here is my servlet code

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String report_path=request.getSession().getServletContext().getInitParameter("REPORT_PATH");

    HouseHoldReportGenerator report = new HouseHoldReportGenerator("HOUSE_HOLD",attrStr_,dbParam);
    report.Write_Report___(report_path, dbParam);
    System.out.println("path-->"+report_path+report.getFileName_());}

I have my report generation java class as HouseHoldReportGenerator. It generates the report. But What I want from one click on the link in jsp page I want it to be generated and downloaded. I can get the report destination also.

Dinidu Hewage
  • 2,169
  • 6
  • 40
  • 51

2 Answers2

1

you should add the following in your servlet method..

try{
        //This is for downloading
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=nameOfExcel");    
        File file = new File("path_to_the_file/excelfile.xls"); //<- the name of excel that you have already created.
        FileInputStream fileIn = new FileInputStream(file);
        ServletOutputStream out = response.getOutputStream();

        byte[] outputByte = new byte[4096];
        //copy binary contect to output stream
        while(fileIn.read(outputByte, 0, 4096) != -1)
        {
                out.write(outputByte, 0, 4096);
        }
        fileIn.close();
        out.flush();
        out.close();
  }
  catch(IOException e){
        e.printStackTrace();
  }
yaylitzis
  • 5,354
  • 17
  • 62
  • 107
0

Look at that answer: https://stackoverflow.com/a/14281064/5594550

Basically you need to set a correct HTTP header and then stream the file to the client through response.getOutputStream()

Community
  • 1
  • 1
ogugger
  • 122
  • 6