您好,登錄后才能下訂單哦!
本篇內容介紹了“ASP.NET MVC怎么把表格導出到Excel”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
有關Model:
namespace MvcApplication1.Models { public class Coach { public int Id { get; set; } public string Name { get; set; } } }
HomeController中,借助GridView控件把內容導出到Excel:
using System.Collections.Generic; using System.IO; using System.Linq; using System.Web.Mvc; using System.Web.UI; using MvcApplication1.Models; namespace MvcApplication1.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(GetCoaches()); } private List<Coach> GetCoaches() { return new List<Coach>() { new Coach(){Id = 1, Name = "斯科拉里"}, new Coach(){Id = 2, Name = "米西維奇"} }; } public void ExportClientsListToExcel() { var grid = new System.Web.UI.WebControls.GridView(); grid.DataSource = from item in GetCoaches() select new { 編號 = item.Id, 主教練 = 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 = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); grid.RenderControl(htw); Response.Write(sw.ToString()); Response.End(); } } }
Home/Index.cshtml強類型集合視圖:
@model IEnumerable<MvcApplication1.Models.Coach> @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <table> <tr> <th>編號</th> <th>主教練</th> </tr> @foreach (var item in Model) { <tr> <td>@item.Id</td> <td>@item.Name</td> </tr> } </table> <br/> @Html.ActionLink("導出到Excel","ExportClientsListToExcel")
“ASP.NET MVC怎么把表格導出到Excel”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。