using NPOI.SS.UserModel; using NPOI.Util.Collections; using NPOI.XSSF.UserModel; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace WIDESEAWCS_Common.Helper { public static class TExportHelper { /// /// 导出 /// public static string GetExport(string savePath, PropertyInfo[] properties, List dataList) { string filePath = ""; try { // 创建 Excel 工作簿 IWorkbook workbook = new XSSFWorkbook(); ISheet sheet = workbook.CreateSheet("x"); // 创建表头行 IRow headerRow = sheet.CreateRow(0); sheet.DefaultColumnWidth = 15; // 设置表头样式 ICellStyle headerStyle = workbook.CreateCellStyle(); IFont headerFont = workbook.CreateFont(); headerFont.Boldweight = (short)FontBoldWeight.Bold; headerFont.FontHeightInPoints = 12; headerStyle.SetFont(headerFont); headerStyle.FillForegroundColor = IndexedColors.LightBlue.Index; headerStyle.FillPattern = FillPattern.SolidForeground; headerStyle.BorderBottom = BorderStyle.Thin; headerStyle.BorderTop = BorderStyle.Thin; headerStyle.BorderLeft = BorderStyle.Medium; headerStyle.BorderRight = BorderStyle.Medium; // 设置数据样式 ICellStyle dataStyle = workbook.CreateCellStyle(); dataStyle.BorderBottom = BorderStyle.Thin; dataStyle.BorderTop = BorderStyle.Thin; dataStyle.BorderLeft = BorderStyle.Thin; dataStyle.BorderRight = BorderStyle.Thin; // 填充表头 for (int i = 0; i < properties.Length; i++) { var columnName = AttributeHelper.GetExporterDisplayName(properties[i]); var cell = headerRow.CreateCell(i); cell.SetCellValue(columnName); cell.CellStyle = headerStyle; } // 填充数据 for (int rowIdx = 0; rowIdx < dataList.Count; rowIdx++) { IRow dataRow = sheet.CreateRow(rowIdx + 1); var item = dataList[rowIdx]; for (int colIdx = 0; colIdx < properties.Length; colIdx++) { var cell = dataRow.CreateCell(colIdx); var value = properties[colIdx].GetValue(item); // 处理不同类型的值 if (value == null) { cell.SetCellValue(""); } else if (value is DateTime dateTime) { cell.SetCellValue(dateTime.ToString("yyyy-MM-dd HH:mm:ss")); } else if (value is bool boolValue) { cell.SetCellValue(boolValue); } else { cell.SetCellValue(value.ToString()); } cell.CellStyle = dataStyle; } } // 保存文件 string fileName = "x.xlsx"; filePath = Path.Combine(savePath, fileName); using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { workbook.Write(fs); } } catch (Exception) { throw; } return filePath; } } }