wayne on February 1, 2008
The following class can be implemented in any project where you need to provide GridView data to end users via an Excel download. This is the starting point for this class, and I have intentions of expanding to provide functionality for other MS Office applications, as well as other data sources beyond the GridView. It is meant to be able to slap into a project and use right away. NOTE! This class assumes ASP.Net, however it can be easily changed to suit Winforms development as well.
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
/// <summary>
/// The ExportData class provides various methods for providing
/// downloadable data to end users
/// </summary>
public static class ExportData
{
/// <summary>
/// The ToExcel procedure will accept a GridView object and provide
/// the contents of the grid to the end user as a downloadable Excel file.
/// </summary>
/// <example>
/// The following shows how to implement this class.
/// <![CDATA[
/// GridView gv = new GridView(); // Create a new grid
/// gv.DataSource = GetData.GetClaimsCodes(); // bind your data
/// gv.DataBind();
/// ExportData.ToExcel(gv); // pass to ExportData
/// ]]>
/// </example>
/// <param name="grid">A populated GridView object to export</param>
public static void ToExcel(GridView grid)
{
/// These writers will take the grid and write them
/// to a stream. The end user sees this as a download
System.IO.StringWriter oStringWriter = null;
System.Web.UI.HtmlTextWriter oHtmlTextWriter = null;
try
{
// Get the current Response object
HttpResponse response = HttpContext.Current.Response;
// Clear the response and prepare it for the Excel download
response.Clear();
response.Buffer = true;
response.ContentType = "application/vnd.ms-excel";
response.Charset = "";
// Define our writers
oStringWriter = new System.IO.StringWriter();
oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
// Render the contents of the grid to the writer
grid.RenderControl(oHtmlTextWriter);
// Write the writers to the response object and end
response.Write(oStringWriter.ToString());
response.End();
}
catch { throw; }
finally
{
// clean up
oHtmlTextWriter.Close();
oHtmlTextWriter.Dispose();
oStringWriter.Close();
oStringWriter.Dispose();
}
}
}