Saturday, January 30, 2010

Download to Excel

Albeit plethora of approaches traditionally followed, the one that impress me is the following.

Assuming datasource is readily available in hand, all we need to do is to export a part of the contents of the result set.

A handy and pliant approach to Download the page contents to Excel using ASP.Net is directly setting the dataset as a source for the response data. There is a small glitch in this as we have to disturb the code every time whenever the data source of the dataset is changed. Instead we can loosely couple this architecture by using XSL in place, provided the XSL file should be in a location which can be directly modified even in PROD similar to config files.

.Net snippet to achieve this:

Response.ClearContent();

Response.ClearHeaders();

Response.ContentType = "application/vnd.ms-excel";

Response.AddHeader("Content-Disposition", "Attachment; FileName =TestDownload);

Response.Charset = "";

XmlDataDocument xdd = new XmlDataDocument(oDS);

xdd.InnerText.Replace("\"", "'");

XslCompiledTransform xt = new XslCompiledTransform();

xt.Load(HttpContext.Current.Server.MapPath(C:\\Excel.xsl");

xt.Transform(xdd, null, Response.OutputStream);

xdd = null;

xt = null;

Response.Flush();

Response.Close();

this.Dispose();

XSL file can be used to control the display of the Excel including the column that are required, format , style etc.,

No comments: