Wednesday, March 14, 2012

Export the contents of a GridView to an Office 2007 Excel file

One of our testers recently asked me if there was a quick way to export the contents of a GridView control to an Office 2007 Excel output file.  After a bit of research, I was able to put together a functional solution that works, but is something that I'd be hesitant to use in a Production environment.  Perhaps this may inspire you to find a more optimal solution, but here is the quick solution that actually works:

First, you will need to add a button control to the aspx page on which the GridView is hosted as follows:

 <asp:Button runat="server" ID="btnExportToExcel" Text="Export to Excel"
        onclick="btnExportToExcel_Click" />

Next, you will need to add the following C# code to the aspx.cs file that is initiated by the button onclick event:

protected void btnExportToExcel_Click(object sender, EventArgs e)
{
    if (GridViewDisplay.Rows.Count > 0)
    {
        string outputFileName = "GetActivePropertiesByMarket.xls";
        // Prep the Response object to return the data as a file/attachment
        Response.Clear();
        Response.Charset = string.Empty;
        Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", outputFileName));
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = outputFileName;
        // Obtain the data from the data source
        // NOTE: For the purposes of this example, I'm referencing a web method; however, you will probably use another means...
        ePM_New.YardiPropertySearchWS service = new ePM_New.YardiPropertySearchWS();
        DataSet ds = service.GetActivePropertiesByMarket(market);
        DataView dv = new DataView(ds.Tables[0]);
        // Bind the data to a second GridView that will be written to the output file...
        GridView grid = new GridView();
        grid.DataSource = dv;
        grid.DataBind();
        // Establish a means of writing the contents of the GridView to the output file
        System.IO.StringWriter sw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(sw);
        grid.RenderControl(htmlWriter);
        Response.Write(sw.ToString());
        Response.End();
    }
}

Once you've updated your data source, you can fire up your web app and test the process of exporting the .xls document by clicking on the Export to Excel button. NOTE: That first IF statement you see in this code verifies that data is actually being displayed in the GridView that is exposed to the user on the web page.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.