Excel Export - ASP.NET MVC

Overview

This article outlines how to export data from an ASP.NET MVC web application to Excel.

Details

[HttpPost]
public ActionResult ExportToExcel(ClaimSearchViewModel viewModel)
{
    // Execute the query
    IQueryable<ClaimSearchResult> results = GetClaimSearchResult(viewModel);

    // Prep a GridView control
    GridView grid = new GridView();
    grid.DataSource = results;
    grid.DataBind();

    // Prep the Response object
    Response.ClearContent();
    Response.AddHeader("content-disposition", "attachment; filename=ClaimSearchResults.xls");
    Response.ContentType = "application/ms-excel";

    // Prep writer objects
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);

    // Render the grid contents => the writer objects => Response object
    grid.RenderControl(htw);
    Response.Write(sw.ToString());

    // Clean up
    Response.End();
    return View("Index"); 
}