在不少系统中都用到导出,使用过多种导出方式,以为ClosedXML插件的导出简单又方便。c++
而且ClosedXML、DocumentFormat.OpenXml都是MIT开源。浏览器
首先经过 Nuget 安装 ClosedXML 插件,同时会自动安装 DocumentFormat.OpenXml 插件。缓存
如下就是导出相关的代码:app
一、MVC控制器中的导出this
// MVC 控制器中 /// <summary> /// 导出 (不管是否须要返回值,都有 Response) /// </summary> public void Export1() // 传入搜索条件 { // 一、根据条件查询到想要的数据 DataTable data = new DataTable(); // 二、设置表名(对应sheet名)、列名(对应列名) data.TableName = "XX统计"; // 三、列宽设置(须要慢慢设置) int[] colsWidth = new int[] { 160, 200, 300, 160 }; // 四、生成导出文件 byte[] filedata = ExportHelper.ExportExcel(data); // 五、输出文件流 HttpContext.Output(filedata, "XX统计_导出" + DateTime.Today.ShowDate() + ".xlsx"); }
二、生成导出文件spa
using ClosedXML.Excel; using System.Data; using System.IO; /// <summary> /// 导出Excel文件 /// </summary> /// <param name="data">导出的数据</param> /// <param name="colsWidth">列宽</param> /// <returns></returns> public static byte[] ExportExcel(DataTable data, int[] colsWidth = null) { using (XLWorkbook workbook = new XLWorkbook()) { IXLWorksheet worksheet = workbook.AddWorksheet(data.TableName); // 处理列 for (int i = 0; i < data.Columns.Count; i++) { worksheet.Cell(1, i + 1).Value = data.Columns[i].ColumnName; worksheet.Cell(1, i + 1).Style.Font.Bold = true; } // 处理列宽 if (colsWidth != null) { for (int j = 1; j <= colsWidth.Length; j++) { worksheet.Columns(j, j).Width = colsWidth[j - 1]; } } // 处理数据 int r = 2;// 第二行开始 foreach (DataRow dr in data.Rows) { // 第一列开始 for (int c = 1; c <= data.Columns.Count; c++) { worksheet.Cell(r, c).Value = data.Rows[r][c].ToString(); } r++; } // 缓存到内存流,而后返回 using (MemoryStream stream = new MemoryStream()) { workbook.SaveAs(stream); return stream.ToArray(); } } }
三、输出文件流插件
using System.Text; using System.Text.RegularExpressions; using System.Web; /// <summary> /// 输出文件流 /// </summary> /// <param name="httpContext">Http上下文</param> /// <param name="filedata">文件数据</param> /// <param name="fileName">文件名(要后缀名)</param> public static void Output(this HttpContextBase httpContext, byte[] filedata, string fileName) { //文件名称效验 文件名不能包含\/:*?<>| 其中\须要两次转义 if (Regex.IsMatch(fileName, @"[\\/:*?<>|]")) { fileName = Regex.Replace(fileName, @"[\\/:*?<>|]", "_"); } //判断是否为火狐浏览器(下载时,有些浏览器中文名称乱码) if (httpContext.Request.Browser.Browser != "Firefox") { fileName = HttpUtility.UrlEncode(fileName, Encoding.UTF8); } // 没有定义类型,用二进制流类型的MIME string MIME = "application/octet-stream"; httpContext.Response.Clear(); httpContext.Response.Buffer = true; //该值指示是否缓冲输出,并在完成处理整个响应以后将其发送 httpContext.Response.ContentType = MIME; httpContext.Response.ContentEncoding = Encoding.UTF8; httpContext.Response.Charset = Encoding.UTF8.HeaderName; httpContext.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); httpContext.Response.AddHeader("Accept-Language", "zh-cn"); httpContext.Response.AddHeader("Content-Length", filedata.LongLength.ToString()); httpContext.Response.BinaryWrite(filedata); httpContext.Response.Flush(); httpContext.Response.End(); }
经过ClosedXML导出操做方便。code