Search code examples
javaexcelservletsdownloadcontent-type

Download Excel from Servlet


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();

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

� ������������ �������� ������������ �������� ������������ �������� ������������ �������� ������������ ��������� ������������ ��������� ������������ ��������� ������������ ��������� ������������ ��������� ������������ ��������� ������������ ��������� ������������ ��������� ������������ ��������� ������������ ��������� ������������ �������� ������������ ����+��� ������������ ����)��� ������������ ����,��� ������������ ����*��� ������������ ���� ��� ������������ ��������������������������`�����������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.


Solution

  • 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.