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

Excel Export - ASP.NET MVC

RSS
Modified on Wed, Jan 11, 2012, 12:23 PM by Administrator Categorized as 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"); 
}

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