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