2015-12-02 30 views
0

我已經使用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頁面中的鏈接,我希望它被生成和下載。我也可以得到報告的目的地。

回答

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