Export to Excel in ASP.Net

Posted: May 25, 2007 in ASP.Net

This is code for exporting a DataSet content into excel report and sending it to client through browser. The client should have Office 2003 atleast installed on this system.

A excel file will be initially created at the server end and then it is sent to the client through the browser.

Also, the thread abort exception occurs here because we are causing the Response to end. So, we need to suppress the exception.

#region Export to Excel
public void CreateExcelReport(DataSet ds, string reportName)
if (ds != null && ds.Tables.Count > 0)
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
string path = System.IO.Path.GetTempPath();
System.IO.FileStream fs = new System.IO.FileStream((path + “/” + reportName), System.IO.FileMode.OpenOrCreate);
//Clear the Response
//Set the Response headers
Response.AppendHeader(“Content-Type”, “application/vnd.ms-excel”);
Response.AppendHeader(“Content-Disposition”, “attachment; filename=” + fs.Name);
Response.Charset = “”;
//Create an instance of GridView
GridView gridView = new GridView();
//Iterating through each DataTable within the DataSet
foreach (DataTable dataTbl in ds.Tables)
gridView.DataSource = dataTbl;
//Output the gridView contents into HtmlWriter
catch (System.Threading.ThreadAbortException te)
//Suppress ThreadAbort exception
//Cleanup the objects

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s