Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Page History: Excel Export - ASP.NET MVC

Compare Page Revisions



« Older Revision - Back to Page History - Current Revision


Page Revision: Thu, Dec 30, 2010, 12:13 PM


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"); 
}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.