using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using NPOI.SS.Formula.Functions; using System.Reflection; using System.IO; public class Exportmethod { /// <summary> /// 導出Excel表格 /// </summary> /// <typeparam name="T">數據類型</typeparam> /// <param name="listEntity"></param> /// <returns></returns> public static byte[] Output<T>(List<T> listEntity) where T : class { Type entityType = (listEntity?.FirstOrDefault()).GetType(); IWorkbook workbook = new XSSFWorkbook(); ISheet sheet = workbook.CreateSheet("sheet"); var scd = typeof(System.ComponentModel.DisplayNameAttribute); var entityProperties = entityType.GetProperties().Where(item => item.GetCustomAttribute(scd) != null).ToList(); IRow Title = sheet.CreateRow(0); IRow rows = null; for (int i = 0; i < listEntity.Count; i++) { var dbitem = listEntity[i]; rows = sheet.CreateRow(i+1); for (int j = 0; j < entityProperties.Count; j++) { var prop = entityProperties[j]; if (i == 0) { //表頭賦值 var display = prop.GetCustomAttribute(scd) as System.ComponentModel.DisplayNameAttribute; Title.CreateCell(j).SetCellValue(display.DisplayName); } //表格數據 var value = prop.GetValue(dbitem)?.ToString(); rows.CreateCell(j).SetCellValue(value ?? ""); } } using (MemoryStream ms = new MemoryStream()) { workbook.Write(ms); return ms.GetBuffer(); } }
下面是實體模型,需要在前面加DisplayName,這樣做的意義是有多少就生成多少列
/// <summary> /// 視圖模型 /// </summary> public class QueryListDataDto { /// <summary> /// ID /// </summary> [DisplayName("編號")] public int Id { get; set; } /// <summary> /// 名稱 /// </summary> [DisplayName("名稱")] public string Name { get; set; } /// <summary> /// 說明 /// </summary> [DisplayName("說明")] public string Description { get; set; }
條件:需要NPOI包