WiredWorx || Web design || SEO || Bournemouth

Web design, website development and search engine optimisation (SEO) in Bournemouth, Dorset, UK.

Exporting to an excel file from ASP.NET MVC


I was intrigued about how to create an excel file from a datasource the other day as ASP.NET MVC obviously is very different from web forms. In web forms there are a hundred and one ways to do this, the easiest we found was to use a plug in such as ASPOSE which then allows you easily to export to a .xls file.

After a bit of searching the t'interweb I stumbled upon this great article from Bill SternBerger. I have also copied and pasted it in below as I'm worried that his blog hasn't been updated for over a year and so it may just disappear one day!

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

using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

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
select new
{
ContactID = contact.ID,
FullName = contact.FullName,
Email = contact.Email
};
grid.DataBind();

Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=YourFileName.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();

That’s it!