Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Generating and downloading Excel file using java

802203Sep 30 2008
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.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 28 2008
Added on Sep 30 2008
0 comments
11,037 views