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

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

你应该在你的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 : //stackoverflow.com/a/14281064/5594550

基本上你需要设置一个正确的HTTP头,然后通过response.getOutputStream()将文件传输到客户端