Exporting a GridView as an Excel File in C#


Exporting information to an excel file is a rather common request. Usually what you are asked to do is add a GridView that has a button that exports the information to an Excel file. The Excel file format is annoying to parse/output and would require a good deal of code to accomplish. However Excel is able to accept HTML tables as input and parse the information properly. So in reality all we need to do is output the GridView to a table and send that as our response. Luckily for us, this is extremely simple to accomplish:

   1: Response.ClearContent();
   2: Response.AddHeader("content-disposition", "attachment; filename=File.xls");
   3: Response.ContentType = "application/ms-excel";
   4: StringWriter Writer = new StringWriter();
   5: HtmlTextWriter HTMLWriter = new HtmlTextWriter(Writer);
   6: MyGridView.RenderControl(HTMLWriter);
   7: Response.Write(Writer.ToString());
   8: Response.End();

The code above takes the GridView (MyGridView) and renders it to an HtmlTextWriter. That in turn is sent out as an attachment with the name of File.xls. Now if you add this to the web page, you're going to run into an issue. It's going to say that you can't render the item unless you're in the Render function... Simply add EnableEventValidation="false" to the page's header. It's very simple but annoying to figure out... Anyway, hopefully this helps you out a bit, so try it out, leave feedback, and happy coding.