为用户创建一个Excel文件使用Apache POI下载 [英] Create an excel file for users to download using Apache POI

查看:110
本文介绍了为用户创建一个Excel文件使用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文件。我读的地方上面code只是说给服务器发送一个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 code,并使用了,而不是一个二进制输出流的字符作家,将因此仅会损坏您的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();

现在,下载它,它的网址,而不是JSP文件调用Servlet。

Now, to download it, invoke the servlet by its URL instead of the JSP file.

这篇关于为用户创建一个Excel文件使用Apache POI下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆