Uncategorized

Export to Excel in Asp.Net MVC

We can render the data as a HTML table and then give the content type as application/excel. Excel renders HTML content in proper format. To convert the Data collection to HTML i’m making use of Asp.Net GridView here. Though this is not very Asp.Net MVC way of doing it this serves the purpose. you could write your own methods to convert the data to html format instead of the gridview here.

Code Snippet
[HttpGet]
public void GetExcel()
{
            reviewDataContext rdc = new reviewDataContext();

            //Bind the Data to Asp.Net DataGrid - you can still use this in Asp.Net MVC though it 
            //cannot be used in the .aspx View
            System.Web.UI.WebControls.GridView grd = new System.Web.UI.WebControls.GridView();
            grd.DataSource = rdc.Reviews.ToList();
            grd.DataBind();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment;filename=test.xls");
            Response.ContentType = "application/excel";

            StringWriter swr = new StringWriter();
            HtmlTextWriter tw = new HtmlTextWriter(swr);
            grd.RenderControl(tw);
            Response.Write(swr.ToString());
            Response.End();
}

2 thoughts on “Export to Excel in Asp.Net MVC

  1. Simply want to say your article is as astounding. The clarity in your post is simply cool and i could assume you are an expert on this subject. Well with your permission let me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please carry on the enjoyable work.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.