gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 10:48:31 24 4
gpt4 key购买 nike

我已经使用 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();
}

关于java - 如何使用 jsp servlet 生成和下载 Excel 报告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34046612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com