Magicodes.IE之快速导出Excel
前言
總是有很多朋友咨詢Magicodes.IE如何基于ASP.NET Core導(dǎo)出Excel,出于從框架的體驗(yàn)和易用性的角度,Magicodes.IE決定對Excel的導(dǎo)出進(jìn)行獨(dú)立封裝,以便于大家更易于使用,開箱即用。
注意:Magicodes.IE是從框架的易用性和體驗(yàn)的角度對Excel導(dǎo)出進(jìn)行了封裝,但是希望大家先理解原理后再使用。
1.安裝包
Install-Package Magicodes.IE.Excel.AspNetCore2.引用命名空間
using Magicodes.ExporterAndImporter.Excel.AspNetCore;
3.直接使用XlsxFileResult
參考Demo如下所示:
[ApiController][Route("api/[controller]")]public class XlsxFileResultTests : ControllerBase{/// <summary>/// 使用Byte數(shù)組導(dǎo)出Excel文件/// </summary>/// <returns></returns>[HttpGet("ByBytes")]public async Task<ActionResult> ByBytes(){//隨機(jī)生成100條數(shù)據(jù)var list = GenFu.GenFu.ListOf<ExportTestDataWithAttrs>(100);var exporter = new ExcelExporter();var bytes = await exporter.ExportAsByteArray<ExportTestDataWithAttrs>(list);//使用XlsxFileResult進(jìn)行導(dǎo)出return new XlsxFileResult(bytes: bytes);}/// <summary>/// 使用流導(dǎo)出Excel文件/// </summary>/// <returns></returns>[HttpGet("ByStream")]public async Task<ActionResult> ByStream(){//隨機(jī)生成100條數(shù)據(jù)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>/// 使用泛型集合導(dǎo)出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之后,導(dǎo)出就會(huì)變得如此簡單。值得注意的是:
使用XlsxFileResult需引用包Magicodes.IE.Excel.AspNetCore
XlsxFileResult繼承自ActionResult,目前支持字節(jié)數(shù)組、流和泛型集合為參數(shù)的Excel文件下載
支持傳遞下載文件名,參數(shù)名fileDownloadName,如不傳則自動(dòng)生成唯一的文件名
核心實(shí)現(xiàn)
在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并且前來解鎖更多玩法。
最后
教程已上傳Github,有興趣有精力的朋友可以幫忙PR一下單元測試,由于精力有限,先手測了,可參考:
ASP.NET Core 中的測試控制器邏輯 | Microsoft Docs
寫個(gè)功能幾分鐘到十幾分鐘,碼個(gè)文檔要半天,就此結(jié)束。
Magicodes.IE:導(dǎo)入導(dǎo)出通用庫,支持Dto導(dǎo)入導(dǎo)出、模板導(dǎo)出、花式導(dǎo)出以及動(dòng)態(tài)導(dǎo)出,支持Excel、Csv、Word、Pdf和Html。
Github:https://github.com/dotnetcore/Magicodes.IE
碼云(手動(dòng)同步,不維護(hù)):https://gitee.com/magicodes/Magicodes.IE
相關(guān)庫會(huì)一直更新,在功能體驗(yàn)上有可能會(huì)和本文教程有細(xì)微的出入,請以相關(guān)具體代碼、版本日志、單元測試示例為準(zhǔn)。
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的Magicodes.IE之快速导出Excel的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 记一次 .NET 某智慧水厂API 非托
- 下一篇: 为什么 Linux 上的 Asp.NET