Tuesday, December 8, 2009

How to programmatically create an Excel Spreadsheet in ASP.net/ C#

The Problem: You need to create a dynamic excel spreadsheet in C#/ASP.net. There are several ways to accomplish this, but this is one I use when I don't need to specify the column names order to any great detail. I've included it in the How To Fix series simply because it took me more than 15 minutes to find the code, and rules are rules.

The Cause: No cause really, this is a method. The cause of hte problem was being a bit disorganized today.

The Solution: Just copy and paste the following code into your C# code behind and let her rip! Utility.dsGrab is just a function that returns a dataset.
DataTable dt = new DataTable();
DataSet ds = Utility.dsGrab("SampleDataSet");
dt = ds.Tables[0];
GridView gv = new GridView();

if (dt.Rows.Count > 0)
{
gv.DataSource = dt;
gv.DataBind();
System.IO.StringWriter oStringWriter =
new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter =
new HtmlTextWriter(oStringWriter);
Response.ClearContent();
Response.ContentType = "application/ms-excel";
Response.AddHeader("Content-Disposition", "attachment;
filename=SampleExcel.xls");
Response.Charset = "";
Response.Buffer = true;
EnableViewState = false;
gv.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}

That's it! It won't open up in the browser window either.

Labels: , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home