Generating and downloading Excel file using java
Dear all,
I have a web application built with jsps and servlets. I have a page showing reports with the resultset from database. How can I generate reports in excel and allow users to download it to their computer.
I have used the jxl library for creating the excel file. The code is given below:
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
OutputStream out = null;
System.out.println("Inside doGet()");
try
{
response.setContentType("application/vnd.ms-excel");
response.setHeader
("Content-Disposition", "attachment; filename=sampleName.xls");
WritableWorkbook w =
Workbook.createWorkbook(response.getOutputStream());
WritableSheet s = w.createSheet("Demo", 0);
s.addCell(new Label(0, 0, "Hello World"));
w.write();
w.close();
}
catch (Exception e)
{
throw new ServletException("Exception in Excel Sample Servlet", e);
}
finally
{
if (out != null)
out.close();
}
}
I am invoking this servlet from a javascript function as follows :
function GeneratePurchaseReport1(){
args="&";
ele=document.forms["PurchaseReport"].elements;
url="/Test/ExcelGen?param=cp&companyname=" + ele[0].value ;
if(window.XMLHttpRequest)
req = new XMLHttpRequest();
else if(window.ActiveXObject)
req = new ActiveXObject("Microsoft.XMLHTTP");
if(req)
{
req.open("GET", url, true);
req.onreadystatechange = function()
{
if(req.readyState == 4)
{
if(req.status == 200){
}
}
};
req.send(null);
}
When I gave the url of the servlet (http://localhost:8080/Test/ExcelGen) in the browser, I got a dialog box asking where to save the file.
When I took my application and tried to generate report the servlet got invoked but it didn't ask where to save the file and the file is not get generated.
Please tell me how to solve this problem. Is there any mistake in the response.setContentType and setHeader methods in my servlet.