C#_.NetCore_WebAPI项目_EXCEL数据导出(ExcelHelper_第二版_优
发布时间:2020-12-16 08:58:12 所属栏目:asp.Net 来源:网络整理
导读:项目需要引用NPOI的Nuget包:DotNetCore.NPOI-v1.2.2 ? 1-简单的设置下载文件的控制器方法: // // 摘要: // / Returns a file with the specified fileContents as content (Microsoft.AspNetCore.Http.StatusCodes.Status200OK), the / specified contentT
项目需要引用NPOI的Nuget包:DotNetCore.NPOI-v1.2.2 ? 1-简单的设置下载文件的控制器方法: // // 摘要: // / Returns a file with the specified fileContents as content (Microsoft.AspNetCore.Http.StatusCodes.Status200OK), the / specified contentType as the Content-Type and the specified fileDownloadName as the suggested file name. / This supports range requests (Microsoft.AspNetCore.Http.StatusCodes.Status206PartialContent or / Microsoft.AspNetCore.Http.StatusCodes.Status416RangeNotSatisfiable if the range is not satisfiable). / 参数: fileContents: The file contents. contentType: The Content-Type of the file. fileDownloadName: The suggested file name. 返回结果: The created Microsoft.AspNetCore.Mvc.FileContentResult for the response. [NonAction] public FileContentResult File(byte[] fileContents,string contentType,1)">string fileDownloadName) //这里以下载txt文件为例: byte[] logByte = System.IO.File.ReadAllBytes(dateLogFilePath); MediaTypeHeaderValue mediaTypeHeaderValue = new MediaTypeHeaderValue("text/plain"); mediaTypeHeaderValue.Encoding = Encoding.UTF8; return File(logByte,mediaTypeHeaderValue.ToString(),date.ToString(yyyy-MM-dd") + .log"); ? 2-本篇文章是对WebAPI项目使用NPOI操作Excel时的帮助类:ExcelHelper的改进优化做下记录: 备注:下面的帮助类代码使用的文件格式为:xlsx文件,xlsx相对xls的优缺点代码里有注释,推荐使用xlsx文件保存数据! ? using Microsoft.AspNetCore.Mvc; Microsoft.Extensions.Logging; Microsoft.Net.Http.Headers; NPOI.SS.UserModel; NPOI.XSSF.UserModel; System; System.Collections.Generic; System.IO; System.Linq; System.Reflection; namespace PaymentAccountAPI.Helper { /// <summary> /// EXCEL帮助类 </summary> <typeparam name="T">泛型类</typeparam> <typeparam name="TCollection">泛型类集合</typeparam> public class ExcelHelp { private ILogger Logger = null; public ExcelHelp(ILogger<ExcelHelp> logger) { this.Logger = logger; } <summary> 将数据导出EXCEL </summary> <param name="tList">要导出的数据集</param> <param name="fieldNameAndShowNameDic">键值对集合(键:字段名,值:显示名称)<param name="fileDirectoryPath">文件路径<param name="excelName">文件名(必须是英文或数字)<returns></returns> public IWorkbook CreateOrUpdateWorkbook<T>(List<T> tList,Dictionary<string,1)">string> fieldNameAndShowNameDic,IWorkbook workbook = null,1)">string sheetName = sheet1") where T : new() { xls文件格式属于老版本文件,一个sheet最多保存65536行;而xlsx属于新版文件类型; Excel 07 - 2003一个工作表最多可有65536行,行用数字1—65536表示; 最多可有256列,列用英文字母A—Z,AA—AZ,BA—BZ,……,IA—IV表示;一个工作簿中最多含有255个工作表,默认情况下是三个工作表; Excel 2007及以后版本,一个工作表最多可有1048576行,16384列; if (workbook == ) { workbook = XSSFWorkbook(); workbook = new HSSFWorkbook(); } ISheet worksheet = workbook.CreateSheet(sheetName); List<string> columnNameList = fieldNameAndShowNameDic.Values.ToList(); 设置首列显示 IRow row1 = worksheet.CreateRow(0); ICell cell = ; ICellStyle cellHeadStyle = workbook.CreateCellStyle(); 设置首行字体加粗 IFont font = workbook.CreateFont(); font.Boldweight = short.MaxValue; cellHeadStyle.SetFont(font); int cloumnCount = columnNameList.Count; for (var i = 0; i < cloumnCount; i++) { cell = row1.CreateCell(i); cell.SetCellValue(columnNameList[i]); cell.CellStyle = cellHeadStyle; } 根据反射创建其他行数据 var raws = tList.Count; Dictionary<this.GetIndexPropertyDic<T>(fieldNameAndShowNameDic); PropertyInfo propertyInfo = ; T t = default(T); int i = 0; i < raws; i++) { if (i % 10000 == ) { this.Logger.LogInformation($Excel已创建{i + 1}条数据); } row1 = worksheet.CreateRow(i + 1); t = tList[i]; int cellIndex = ; foreach (var titlePropertyItem in titlePropertyDic) { propertyInfo = titlePropertyItem.Value; cell = row1.CreateCell(cellIndex); if (propertyInfo.PropertyType == typeof(int) || propertyInfo.PropertyType == decimaldouble)) { cell.SetCellValue(Convert.ToDouble(propertyInfo.GetValue(t) ?? )); } else typeof(DateTime)) { cell.SetCellValue(Convert.ToDateTime(propertyInfo.GetValue(t)?.ToString()).ToString(yyyy-MM-dd HH:mm:ssbool)) { cell.SetCellValue(Convert.ToBoolean(propertyInfo.GetValue(t).ToString())); } else { cell.SetCellValue(propertyInfo.GetValue(t)?.ToString() ?? ""); } cellIndex++; } 重要:设置行宽度自适应(大批量添加数据时,该行代码需要注释,否则会极大减缓Excel添加行的速度!) worksheet.AutoSizeColumn(i,true); } return workbook; } 保存Workbook数据为文件 <param name="workbook"></param> <param name="fileDirectoryPath"></param> <param name="fileName"></param> void SaveWorkbookToFile(IWorkbook workbook,1)">string fileDirectoryPath,1)">string fileName) { Excel 2007及以后版本,一个工作表最多可有1048576行,16384列; MemoryStream ms = MemoryStream(); 这句代码非常重要,如果不加,会报:打开的EXCEL格式与扩展名指定的格式不一致 ms.Seek(,SeekOrigin.Begin); workbook.Write(ms); byte[] myByteArray = ms.GetBuffer(); fileDirectoryPath = fileDirectoryPath.TrimEnd('') + ; if (!Directory.Exists(fileDirectoryPath)) { Directory.CreateDirectory(fileDirectoryPath); } string filePath = fileDirectoryPath + fileName; if (File.Exists(filePath)) { File.Delete(filePath); } File.WriteAllBytes(filePath,myByteArray); } 保存Workbook数据为下载文件 </summary> public FileContentResult SaveWorkbookToDownloadFile(IWorkbook workbook) { MemoryStream ms = ms.GetBuffer(); 对于.xls文件 application/vnd.ms-excel 用于.xlsx文件。 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet MediaTypeHeaderValue mediaType = application/vnd.openxmlformats-officedocument.spreadsheetml.sheet); mediaType.Encoding = System.Text.Encoding.UTF8; //设置下载文件名 ? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net Ajax之无刷新评论介绍
- asp.net – 为会话设置文化
- asp.net-mvc-5 – EntityFramework.SqlServer.dll中出现’S
- asp.net核心 – 是否可以自主托管没有IIS(不是Web API)的AS
- ASP.NET MVC 4 – 应用程序不接受新连接字符串 – AppHarbo
- asp.net-mvc-3 – 在ASP.NET MVC中使用@ data-bind htmlAtt
- asp.net – 无法完成操作.提供的SqlConnection不指定初始目
- asp.net – IIS 6如何从http://example.com/*重定向到http:
- asp.net – 我可以在DefaultModelBinder上禁用DataAnnotati
- ASP.NET C#会话变量丢失
推荐文章
站长推荐
- asp.net-mvc – 使用MSpec测试ActionFilterAttri
- asp.net-mvc – MVC Model Binding不适用于Kendo
- asp.net-mvc – ASP.Net MVC中的两步认证
- 如何在ASP.NET MVC4 Web API中捕获未定义的api方
- asp.net – UpdatePanel中的动态创建控件?
- asp.net-mvc – MVC获得管理层批准
- 扩展UltraGrid控件实现对所有数据行的全选功能[S
- ASP.Net自定义会话状态管理
- asp.net-mvc-2 – 如何通过ASP.NET MVC 2.0中的t
- asp.net-mvc-3 – mvc3 – 在不同的区域使用部分
热点阅读