创建一个excel文件供用户使用Apache POI下载 [英] Create an excel file for users to download using Apache POI
问题描述
我可以使用 apache poi 创建一个 excel 文件.但是,我希望用户能够将其下载为真正的"excel 文件.我想要达到的效果是有一个弹出框,允许用户下载文件.这类似于使用
I'm able to create an excel file using apache poi. however, i want users to be able to download this as a "true" excel file. the effect i want to achieve would be to have a popup box allowing the user to download the file. this is similar to using
<%@ page contentType="application/vnd.ms-excel" pageEncoding="ISO-8859-1"%>
<%response.setHeader("Content-Disposition", "attachment;filename=myfile.xls"); %>
有一个严重的例外:我必须允许用户下载正确的 excel 文件.我在某处读到上面的代码只是对客户端说服务器正在发送一个 excel 文件
with one critical exception: i must allow the user to download a proper excel file. i read somewhere the above code simply says to the client that the server is sending an excel file
推荐答案
在普通的 servlet 而不是 JSP 文件中完成这项工作.JSP 文件用于动态生成 HTML 代码,并为此使用字符编写器而不是二进制输出流,因此只会损坏您的 POI 生成的 Excel 文件,该文件本质上是二进制流.
Do the job in a normal servlet instead of a JSP file. A JSP file is meant for dynamically generating HTML code and is using a character writer for that instead of a binary output stream and would thus only corrupt your POI-generated Excel file which is in essence a binary stream.
因此,基本上您需要在 servlet 的 doGet()
方法中执行以下操作:
So, basically all you need to do in the doGet()
method of the servlet is the following:
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=filename.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
// ...
// Now populate workbook the usual way.
// ...
workbook.write(response.getOutputStream()); // Write workbook to response.
workbook.close();
现在,要下载它,请通过其 URL 而不是 JSP 文件调用 servlet.
Now, to download it, invoke the servlet by its URL instead of the JSP file.
这篇关于创建一个excel文件供用户使用Apache POI下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!