Export to Excel or CSV from ASP.NET MVC with C#

Filed in ASP.NET MVC | C# 3 Comments

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!

, , , ,

How to remove & nbsp; from string in c#

Filed in C# 1 Comment

Here is a line of code to remove all occurrences of   – or any other string for that matter – in a single shot. Ready for this complex feat of engineering?? Ok, here it is:

string theResult = someString.Replace(“ ”,”");

That’s it!

TOP