使用Epplus以及Excel将模板导出excel
1、核心逻辑(为了测试方便,路径直接写死了):
public static void TemplateWrite<T>(List<T> datas, int startRow = 2, string targetPath = @"D:\导出excel测试.xlsx", string templatePath = @"D:\github\Demo\NetCoreDemo\src\ExcelDemo\Template\template.xlsx") { var stream = FileToStream(templatePath); using (ExcelPackage package = new OfficeOpenXml.ExcelPackage(stream)) {
//注意:引用的如果是Epplus.core。sheet是从1开始的,如果引用的是Epplus,sheet是从0开始的。 ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
startRow = 3; Type myType = typeof(T); var pros = myType.GetProperties(); foreach (var data in datas) { worksheet.Cells.AutoFitColumns();//自适应宽度 var column = 1; foreach (var item in pros) { //遍历赋值:前提是要顺序一致。 var value = item.GetValue(data, null); worksheet.Cells[startRow, column].Value = value; column++; } startRow++; } FileInfo fs = new FileInfo(targetPath); package.SaveAs(fs); } }
2、测试Model
public class Students { public string Name { get; set; } public int Age { get; set; } public int ClassNum { get; set; } public decimal Math { get; set; } public decimal Lang { get; set; } public string dec { get; set; } }
3、模板
4、调用方法:
static void Main(string[] args) { Console.WriteLine("Hello World!"); List<Students> students = new List<Students>(); students.Add(new Students() { Name = "张三", Age = 5, ClassNum = 6, Lang = 90, Math = 89,dec= "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" }); students.Add(new Students() { Name = "李四", Age = 8, ClassNum = 5, Lang = 70, Math = 99, dec = "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" }); EpplusExcelHelper.TestTemplateWrite(students); }
5、运行,查看运行结果: