MVC exports tables to Excel

Source: Internet
Author: User

About Model:

namespace mvcapplication1.models{    publicclass  Coach    {        public  intgetset;}          Public string Get Set ; }    }}

HomeController, use the GridView control to export the content to Excel:

usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSYSTEM.WEB.MVC;usingSystem.Web.UI;usingMvcapplication1.models;namespacemvcapplication1.controllers{ Public classHomecontroller:controller { PublicActionResult Index () {returnView (Getcoaches ()); }        PrivateList<coach>getcoaches () {return NewList<coach>()            {                NewCoach () {Id =1, Name ="Scolari"},                NewCoach () {Id =2, Name ="Missivichi"}            }; }         Public voidExportclientslisttoexcel () {varGrid =NewSystem.Web.UI.WebControls.GridView (); Grid. DataSource= fromIteminchgetcoaches ()Select New{Number=item. Id, Coach=item.            Name}; Grid.            DataBind ();            Response.clearcontent (); Response.AddHeader ("content-disposition","attachment; Filename=exported_coaches.xls"); Response.ContentType="Application/excel"; Response.Charset="Utf-8"; Response.ContentEncoding= System.Text.Encoding.GetEncoding ("GB2312"); StringWriter SW=NewStringWriter (); HtmlTextWriter HTW=NewHtmlTextWriter (SW); Grid.            RenderControl (HTW); Response.Write (SW.            ToString ());        Response.End (); }    }}

Home/index.cshtml strongly typed collection view:

@model ienumerable<mvcapplication1.models.coach>@{Viewbag.title="Index"; Layout="~/views/shared/_layout.cshtml";}<table> <tr> <th> numbering </th> <th> manager </th> </tr>@foreach (varIteminchModel) {        <tr> <td> @item. Id</td> <td> @item. Name</td> </tr>    }</table><br/>@Html. ActionLink ("Export to Excel","Exportclientslisttoexcel")

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.