如何使用jsp servlet生成和下载Excel报告

时间:2015-12-02 15:32:30

标签: java excel jsp

我使用Apache POI生成了Excel报告。我现在想要的,我想将它发送到浏览器下载。我的JSP如下。

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

这是我的servlet代码

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_());}

我的报告生成java类为HouseHoldReportGenerator。它会生成报告。但是我想通过点击jsp页面中的链接我想要生成和下载它。我也可以获得报告目的地。

2 个答案:

答案 0 :(得分:1)

您应该在servlet方法中添加以下内容。

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();
  }

答案 1 :(得分:0)

看看答案:https://stackoverflow.com/a/14281064/5594550

基本上您需要设置正确的HTTP标头,然后通过response.getOutputStream()

将文件流式传输到客户端