C#实现NPOI的Excel导出详解
这篇文章主要介绍了C#实现NPOI的Excel导出的示例代码,文中的实现过程讲解详细,对我们的学习或工作有一定的帮助,感兴趣的可以跟随小编一起学习一下
技术点:
1.自定义attribute
属性
2.通过反射取类及其属性的attribute
属性值
3.NPOI包常用属性及方法(我也仅仅知道用到过的,陌生的要么见名知意,要么百度查)
实现功能点:
List类对象的模板导出,实用场景例子见最后代码块(emm...还是比较抽象,代码见)
EXCEL导出类DTO超类
定义继承导出类DTO的特性说明类
Excel帮助类
这部分要讲的点其实挺多的,关键就是EXCEL导出所用到的数据源是强类型的。
可以看出来list
其实是EF的Queryable
toList()
后的类集合,作为数据源存在
里面的DTO DesWeeklyReportExcExp
继承ExcelSuper
,特性分别加在类及属性上。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | public class XXXXController : CoreController { // 控制器内部 [HttpPost] public ActionResult export() { // 控制器接口 var list = op .GetPagedQuery(PageModel) .Select(s => new DesWeeklyReportExcExp { col1 = s.Project.ProjName, col2 = s.ColAttROPDate1?.ToString( "yyyy.MM.dd" ), col3 = (s.ColAttROPDate2 == null ? "无" : s.ColAttROPDate2.Value.ToString( "yyyy.MM.dd" )) + "/" + (s.ColAttROPDate3 == null ? "无" : s.ColAttROPDate3.Value.ToString( "yyyy.MM.dd" )), col4 = s.ColAttROPDate4?.ToString( "yyyy.MM.dd" ) }).ToList(); string filePath = Server.MapPath( "~/download/[这是模板名称].xlsx" ); string filename = Path.GetFileNameWithoutExtension(filePath); // 文件名称 string extension = Path.GetExtension(filePath); // 后缀名 带点(.) string fileDownloadName = filename + extension; var fs = ExcelHelper.ExportToExcel(list, filePath).ToArray(); return File(fs, "application/ms-excel" , fileDownloadName); } } [ExcelExpClassAttribute(2, 0, 2, 0)] public class DesWeeklyReportExcExp : ExcelSuper { /// <summary> /// 列1 /// </summary> [ExcelExp(SortIndex = 0, ColName = "列1" )] public string col1 { get ; set ; } /// <summary> /// 列2 /// </summary> [ExcelExp(SortIndex = 0, ColName = "列2" )] public string col2 { get ; set ; } /// <summary> /// 列3 /// </summary> [ExcelExp(SortIndex = 0, ColName = "列3" )] public string col3 { get ; set ; } /// <summary> /// 列4 /// </summary> [ExcelExp(SortIndex = 0, ColName = "列4" )] public string col4 { get ; set ; } } |
到此这篇关于C#实现NPOI的Excel导出详解的文章就介绍到这了
原文链接:https://www.cnblogs.com/codeJJ/p/15822938.html