前言
總是有很多朋友諮詢Magicodes.IE如何基於ASP.NET Core匯出Excel,出於從框架的體驗和易用性的角度,決定對Excel的匯出進行獨立封裝,以便於大家更易於使用,開箱即用。
注意:Magicodes.IE是從框架的易用性和體驗的角度對Excel匯出進行了封裝,但是希望大家先理解原理後再使用。
1.安裝包
Install-Package Magicodes.IE.Excel.AspNetCore
2.引用名稱空間
using Magicodes.ExporterAndImporter.Excel.AspNetCore;
3.直接使用XlsxFileResult
參考Demo如下所示:
[ApiController]
[Route("api/[controller]")]
public class XlsxFileResultTests : ControllerBase
{
/// <summary>
/// 使用Byte陣列匯出Excel檔案
/// </summary>
/// <returns></returns>
[HttpGet("ByBytes")]
public async Task<ActionResult> ByBytes()
{
//隨機生成100條資料
var list = GenFu.GenFu.ListOf<ExportTestDataWithAttrs>(100);
var exporter = new ExcelExporter();
var bytes = await exporter.ExportAsByteArray<ExportTestDataWithAttrs>(list);
//使用XlsxFileResult進行匯出
return new XlsxFileResult(bytes: bytes);
}
/// <summary>
/// 使用流匯出Excel檔案
/// </summary>
/// <returns></returns>
[HttpGet("ByStream")]
public async Task<ActionResult> ByStream()
{
//隨機生成100條資料
var list = GenFu.GenFu.ListOf<ExportTestDataWithAttrs>(100);
var exporter = new ExcelExporter();
var result = await exporter.ExportAsByteArray<ExportTestDataWithAttrs>(list);
var fs = new MemoryStream(result);
return new XlsxFileResult(stream: fs, fileDownloadName: "下載檔案");
}
/// <summary>
/// 使用泛型集合匯出Excel檔案
/// </summary>
/// <returns></returns>
[HttpGet("ByList")]
public async Task<ActionResult> ByList()
{
var list = GenFu.GenFu.ListOf<ExportTestDataWithAttrs>(100);
return new XlsxFileResult<ExportTestDataWithAttrs>(data: list);
}
}
如上所示,引用 Magicodes.IE.Excel.AspNetCore
之後,匯出就會變得如此簡單。值得注意的是:
- 使用
XlsxFileResult
需引用包Magicodes.IE.Excel.AspNetCore
XlsxFileResult
繼承自ActionResult
,目前支援位元組陣列、流和泛型集合為引數的Excel檔案下載- 支援傳遞下載檔名,引數名
fileDownloadName
,如不傳則自動生成唯一的檔名
核心實現
在Magicodes.IE.Excel.AspNetCore
中,我們新增了自定義的ActionResult
——XlsxFileResult
,核心參考程式碼如下所示:
/// <summary>
/// Excel檔案ActionResult
/// </summary>
/// <typeparam name="T"></typeparam>
public class XlsxFileResult<T> : XlsxFileResultBase where T : class, new()
{
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="fileDownloadName"></param>
public XlsxFileResult(ICollection<T> data, string fileDownloadName = null)
{
FileDownloadName = fileDownloadName;
Data = data;
}
public string FileDownloadName { get; }
public ICollection<T> Data { get; }
public async override Task ExecuteResultAsync(ActionContext context)
{
var exporter = new ExcelExporter();
var bytes = await exporter.ExportAsByteArray(Data);
var fs = new MemoryStream(bytes);
await DownloadExcelFileAsync(context, fs, FileDownloadName);
}
}
/// <summary>
///
/// </summary>
public class XlsxFileResult : XlsxFileResultBase
{
/// <summary>
///
/// </summary>
/// <param name="stream"></param>
/// <param name="fileDownloadName"></param>
public XlsxFileResult(Stream stream, string fileDownloadName = null)
{
Stream = stream;
FileDownloadName = fileDownloadName;
}
/// <summary>
///
/// </summary>
/// <param name="bytes"></param>
/// <param name="fileDownloadName"></param>
public XlsxFileResult(byte[] bytes, string fileDownloadName = null)
{
Stream = new MemoryStream(bytes);
FileDownloadName = fileDownloadName;
}
public Stream Stream { get; protected set; }
public string FileDownloadName { get; protected set; }
public async override Task ExecuteResultAsync(ActionContext context)
{
await DownloadExcelFileAsync(context, Stream, FileDownloadName);
}
}
/// <summary>
/// 基類
/// </summary>
public class XlsxFileResultBase : ActionResult
{
/// <summary>
/// 下載Excel檔案
/// </summary>
/// <param name="context"></param>
/// <param name="stream"></param>
/// <param name="downloadFileName"></param>
/// <returns></returns>
protected virtual async Task DownloadExcelFileAsync(ActionContext context,
Stream stream,
string downloadFileName)
{
var response = context.HttpContext.Response;
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
if (downloadFileName == null)
{
downloadFileName = Guid.NewGuid().ToString("N") + ".xlsx";
}
if (string.IsNullOrEmpty(Path.GetExtension(downloadFileName)))
{
downloadFileName += ".xlsx";
}
context.HttpContext.Response.Headers.Add("Content-Disposition", new[] {
"attachment; filename=" +HttpUtility.UrlEncode(downloadFileName)
});
await stream.CopyToAsync(context.HttpContext.Response.Body);
}
}
歡迎大家多多PR並且前來解鎖更多玩法。
知識點總結
敲黑板,麻煩有空幫點點,為了德瑪西亞:
ASP.NET Core Web API 中控制器操作的返回型別 | Microsoft Docs
Reference
https://github.com/dotnetcore/Magicodes.IE
最後
有興趣有精力的朋友可以幫忙PR一下單元測試,由於精力有限,先手測了,參考:
ASP.NET Core 中的測試控制器邏輯 | Microsoft Docs
寫個功能幾分鐘到十幾分鍾,碼個文件要半天,就此結束。
Magicodes.IE:匯入匯出通用庫,支援Dto匯入匯出、模板匯出、花式匯出以及動態匯出,支援Excel、Csv、Word、Pdf和Html。
- Github:https://github.com/dotnetcore/Magicodes.IE
- 碼雲(手動同步,不維護):https://gitee.com/magicodes/Magicodes.IE
相關庫會一直更新,在功能體驗上有可能會和本文教程有細微的出入,請以相關具體程式碼、版本日誌、單元測試示例為準。