using MESWebSite.CommonClass; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web; namespace MESWebSite.Tool { public class ExcelTool { /// /// 导出Excel /// /// 导出的数据集合类型 /// 导出的数据集合 /// 导出的Excel实体类型 /// public XSSFWorkbook Export(List data, Type type) where T : class { XSSFWorkbook book = new XSSFWorkbook(); ISheet sheet = book.CreateSheet("Sheet1"); IRow hrow = sheet.CreateRow(0); PropertyInfo[] prop = type.GetProperties(); // 通过反射写入表头 WriteHeader(hrow, prop); // 通国反射写入内容 WriteContent(sheet, data, prop); return book; } public void WriteHeader(IRow row, PropertyInfo[] header) { for (int i = 0; i < header.Length; i++) { ICell cell = row.CreateCell(i); var col = header[i]; ExportHeaderAttribute attr = col.GetCustomAttribute(); if (attr == null) { cell.SetCellValue(col.Name); } else { cell.SetCellValue(attr.HeaderName); } } } public void WriteContent(ISheet sheet, List data, PropertyInfo[] header) { for (int i = 0; i < data.Count; i++) { IRow row = sheet.CreateRow(i + 1); for (int j = 0; j < header.Length; j++) { ICell cell = row.CreateCell(j); T o = data[i]; var prop = o.GetType().GetProperty(header[j].Name); if (prop != null) { cell.SetCellValue(prop.GetValue(o).ToString()); } } } } } }