ASP.NET MVC把表格導出到Excel
更新時間:2022年07月31日 14:23:38 作者:Darren Ji
這篇文章介紹了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的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- .NET6導入和導出EXCEL
- Asp.Net Core實現(xiàn)Excel導出功能的實現(xiàn)方法
- ASP.NET Core 導入導出Excel xlsx 文件實例
- asp.net DataTable導出Excel自定義列名的方法
- ASP.NET使用GridView導出Excel實現(xiàn)方法
- Asp.Net使用Npoi導入導出Excel的方法
- asp.net導出excel的簡單方法實例
- asp.net導出Excel類庫代碼分享
- ASP.NET導出數(shù)據(jù)到Excel的實現(xiàn)方法
- Asp.net中DataTable導出到Excel的方法介紹
- ASP.NET用DataSet導出到Excel的方法
- asp.net GridView導出到Excel代碼
相關文章
asp.net繼承IHttpHandler接口實現(xiàn)給網(wǎng)站圖片添加水印功能實例
這篇文章主要介紹了asp.net繼承IHttpHandler接口實現(xiàn)給網(wǎng)站圖片添加水印功能,實例分析了asp.net基于IHttpHandler接口實現(xiàn)網(wǎng)站圖片水印功能的具體步驟與相關技巧,需要的朋友可以參考下2016-07-07
asp.net編程實現(xiàn)刪除文件夾及文件夾下文件的方法
這篇文章主要介紹了asp.net編程實現(xiàn)刪除文件夾及文件夾下文件的方法,涉及asp.net針對文件與目錄的遍歷及刪除操作實現(xiàn)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-11-11
asp.net中DBNull.Value,null,String.Empty區(qū)別淺析
這篇文章來給大家介紹asp.net中DBNull.Value,null,String.Empty區(qū)別淺析,有需要的同學可以參考一下2013-08-08
aspnetcore 實現(xiàn)簡單的偽靜態(tài)化功能
這篇文章主要介紹了aspnetcore 實現(xiàn)簡單的偽靜態(tài)化功能,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-07-07

