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

问题描述:

我已经使用Apache POI生成了Excel报告。我现在想要的,我想发送到浏览器下载。我的JSP如下。如何使用jsp servlet生成和下载Excel报告

<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页面中的链接,我希望它被生成和下载。我也可以得到报告的目的地。

流的文件给客户端,你应该添加在你的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(); 
    } 

看这个问题的答案:https://*.com/a/14281064/5594550

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