Since programming way back in the Classic ASP days, at some point a client always wants to export an html grid into an Excel grid. In c#, that need didn’t disappear, but got a lot easier with GridView and the HtmlTextWriter. Finally reached that point in my ASP.NET MVC programming world, and quite frankly, am surprised it took this long, for this same need! But I digress. To pull this off, all we are really going to do is add an export method to a controller, most of which will look very familiar to asp.net web forms.
Add using statements
We are going to use our dear old friend the GridView from web forms as a placeholder for our data, which is why we need the second using statement.
Create Controller Method
This one is pretty easy, consisting of three parts:
- Creating the GridView placeholder
- Binding the query results to the GridView placeholder
- Dumping the results back to the browser
This example queries all contacts that have not unsubscribed, but you can imagine how easy it is to extend.
var contacts = Contact.FindAll();
var grid = new System.Web.UI.WebControls.GridView();
grid.DataSource = from contact in contacts
where contact.Unsubscribe == false
ContactID = contact.ID,
FullName = contact.FullName,
Email = contact.Email
Response.AddHeader("content-disposition", "attachment; filename=YourFileName.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);