技术点:
1.自定义attribute
属性
2.通过反射取类及其属性的attribute
属性值
3.NPOI包常用属性及方法(我也仅仅知道用到过的,陌生的要么见名知意,要么百度查)
实现功能点:
List类对象的模板导出,实用场景例子见最后代码块(emm...还是比较抽象,代码见)
EXCEL导出类DTO超类
定义继承导出类DTO的特性说明类
Excel帮助类
这部分要讲的点其实挺多的,关键就是EXCEL导出所用到的数据源是强类型的。
可以看出来list
其实是EF的Queryable
toList()
后的类集合,作为数据源存在
里面的DTO DesWeeklyReportExcExp
继承ExcelSuper
,特性分别加在类及属性上。
- 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导出详解的文章就介绍到这了,更多相关C# NPOI的Excel导出内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!