1 /// <summary> 2 /// 将Excel数据转换成DataTable 3 /// </summary> 4 /// <param name="xlsxFile"></param> 5 /// <returns></returns> 6 private List<DataTable> GetDataTablesFromExcel(string xlsxFile) 7 { 8 if (!File.Exists(xlsxFile)) 9 throw new FileNotFoundException("文件不存在"); 10 List<DataTable> dataTableList = new List<DataTable>(); 11 using (FileStream fileStream = new FileStream(xlsxFile, FileMode.Open, FileAccess.Read)) 12 { 13 IWorkbook workbook = !(Path.GetExtension(xlsxFile) == ".xlsx") ? (IWorkbook)new HSSFWorkbook((Stream)fileStream) : (IWorkbook)new XSSFWorkbook((Stream)fileStream); 14 for (int index = 0; index < workbook.NumberOfSheets; index++) 15 { 16 DataTable dataTable = new DataTable(); 17 ISheet sheetAt = workbook.GetSheetAt(index); 18 if (sheetAt==null) 19 { 20 continue; 21 } 22 dataTable.TableName = sheetAt.SheetName; 23 int rowsCount = sheetAt.PhysicalNumberOfRows;//获取Excel的最大行数 24 if (rowsCount <= 1) continue; 25 //为保证Table布局与Excel一样,这里应该取所有行中的最大列数(需要遍历整个Sheet)。 26 //为少一交全Excel遍历,提高性能,我们可以人为把第0行的列数调整至所有行中的最大列数。 27 int colsCount = sheetAt.GetRow(0).PhysicalNumberOfCells; 28 29 //取表格第一行(标题)为Columns 30 for (int i = 0; i < colsCount; i++) 31 { 32 var cellValue = sheetAt.GetRow(0).GetCell(i); 33 dataTable.Columns.Add(cellValue?.ToString()); 34 } 35 36 //从第二行取数据,第一行默认为标题 37 for (int x = 1; x < rowsCount; x++) 38 { 39 DataRow dr = dataTable.NewRow(); 40 for (int y = 0; y < colsCount; y++) 41 { 42 var cellValue = sheetAt.GetRow(x).GetCell(y); 43 dr[y] = cellValue?.ToString(); 44 } 45 dataTable.Rows.Add(dr); 46 } 47 dataTableList.Add(dataTable); 48 } 49 } 50 return dataTableList; 51 }