using NPOI.SS.UserModel; using System; using System.Data; using System.IO; namespace YiDa_WinForm.Utils { /// /// Excel 解析工具类 /// public static class ExcelHelper { /// /// 读取Excel文件转换为DataTable /// /// Excel文件路径 /// 解析后的DataTable public static DataTable GetExcelToDataTable(string filePath) { if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath)) { throw new FileNotFoundException("Excel文件不存在", filePath); } IWorkbook workbook = null; FileStream fileStream = null; try { fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); workbook = WorkbookFactory.Create(fileStream); DataTable dt = new DataTable(); // 读取第一个Sheet(适配你的业务场景,如需多Sheet可扩展) ISheet sheet = workbook.GetSheetAt(0); if (sheet == null) return dt; // 读取表头构建DataTable列 IRow headerRow = sheet.GetRow(0); if (headerRow == null) return dt; for (int i = 0; i < headerRow.LastCellNum; i++) { string columnName = headerRow.GetCell(i)?.ToString() ?? $"列{i + 1}"; dt.Columns.Add(columnName); } // 读取数据行 for (int rowIndex = 1; rowIndex <= sheet.LastRowNum; rowIndex++) { IRow dataRow = sheet.GetRow(rowIndex); if (dataRow == null) continue; DataRow dr = dt.NewRow(); for (int colIndex = 0; colIndex < headerRow.LastCellNum; colIndex++) { ICell cell = dataRow.GetCell(colIndex); dr[colIndex] = GetCellValue(cell); } dt.Rows.Add(dr); } return dt; } finally { // 手动释放资源 if (fileStream != null) { fileStream.Close(); fileStream.Dispose(); } workbook = null; } } /// /// 获取Excel单元格的值(处理不同单元格类型) /// private static string GetCellValue(ICell cell) { if (cell == null) return string.Empty; switch (cell.CellType) { case CellType.Numeric: if (DateUtil.IsCellDateFormatted(cell)) { return cell.DateCellValue.ToString(); } else { return cell.NumericCellValue.ToString(); } case CellType.String: return cell.StringCellValue; case CellType.Boolean: return cell.BooleanCellValue.ToString(); default: return cell.ToString(); } } } }