从Servlet下载Excel [英] Download Excel from Servlet
问题描述
我有以下servlet,我使用GET方法下载使用apache POI生成的Excel文件。
I have following servlet where I use the "GET" method to download an Excel file which I generate using apache POI.
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=reg_user.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Registered Users");
// create workbook
ServletOutputStream out = response.getOutputStream();
workbook.write(out);
out.flush();
out.close();
,我对这个servlet进行ajax调用。但是Excel文件没有下载。当我看着控制台,它有一些奇怪的字符,以及可能的数据来自于所提供的excel文件。
and I make an ajax call to this servlet. But the Excel file is not downloading. When I looked the console, it has some weird characters along with possible data from the supposed excel file
+ ) , * 注册用户 # 用户ID Name
Email地址
手机号码
出生日期Gender Locale 100005085485545
� ������������ �������� ������������ �������� ������������ �������� ������������ �������� ������������ ��������� ������������ ��������� ������������ ��������� ������������ ��������� ������������ ��������� ������������ ��������� ������������ ��������� ������������ ��������� ������������ ��������� ������������ ��������� ������������ �������� ������������ ����+��� ������������ ����)��� ������������ ����,��� ������������ ����*��� ������������ ���� ��� ������������ ��������������������������`�����������Registered Users��������������������#��������User ID��Name ��Email Address ��Mobile Number ��Date of Birth��Gender��Locale��100005085485545
我使用同样的方法将文件写入我的电脑使用以下代码,它的工作。
I used this same method to write the file to my computer using following code and it worked.
FileOutputStream out = new FileOutputStream(new File("C:\\new.xls"));
workbook.write(out);
out.close();
但是我想要的是自动下载文件,因为某些原因不起作用。
But what I want is to auto download the file, which is not working for some reason.
什么是课程?我已经设置了响应内容类型太正确。
What could be the course? I have set the response content type too correctly.
推荐答案
好的,实际上问题是我正在做一个ajax调用。当我使用< a href =reporting.do?type = USERS> User Report< / a>
直接调用servlet时,它工作正常。
okay, actually the problem has to be I am making an ajax call. When I directly invoke the servlet using <a href="reporting.do?type=USERS">User Report</a>
it worked fine.
这篇关于从Servlet下载Excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!