1 public static void ExportExcel<T>(List<T> ts,string filename) 2 { 3 var model = ts.FirstOrDefault(); 4 List<PropertyInfo> titles = model.GetType().GetProperties().ToList(); 5 using (ExcelPackage package = new ExcelPackage()) 6 { 7 // 添加一个工作表 8 ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1"); 9 // 获取第一行用于标题 10 int row = 1; 11 // 对象的第一个元素的所有键,用作Excel的列标题 12 int col = 1; 13 foreach (var title in titles) 14 { 15 worksheet.Cells[row, col].Value = title.Name; 16 col++; 17 } 18 // 填充数据行,从第二行开始 19 row = 2; 20 foreach (var item in ts) 21 { 22 col = 1; 23 List<PropertyInfo> props = item.GetType().GetProperties().ToList(); 24 foreach (var prop in props) 25 { 26 worksheet.Cells[row, col].Value = prop.GetValue(item); 27 col++; 28 } 29 row++; 30 } 31 // 保存Excel文件到磁盘 32 FileInfo excelFile = new FileInfo($"{model.GetType().Name}_{filename}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx"); 33 package.SaveAs(excelFile); 34 } 35 }
引用
<PackageReference Include="EPPlus.Core" Version="1.5.4" />