
1 static public class ImportExcel
2 {
3 public static DataTable GetExcelDataTable(string filePath)
4 {
5 IWorkbook Workbook;
6 DataTable table = new DataTable();
7 try
8 {
9 using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
10 {
11 //XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式
12 string fileExt = Path.GetExtension(filePath).ToLower();
13 if (fileExt == ".xls")
14 {
15 Workbook = new HSSFWorkbook(fileStream);
16 }
17 else if (fileExt == ".xlsx")
18 {
19 Workbook = new XSSFWorkbook(fileStream);
20 }
21 else
22 {
23 Workbook = null;
24 }
25 }
26 }
27 catch (Exception ex)
28 {
29 throw ex;
30 }
31 //定位在第一个sheetActiveSheetIndex
32 ISheet sheet = Workbook.GetSheetAt(0);
33 //int sheet1 = Workbook.NumberOfSheets;//总共有多少页码
34 //第一行为标题行
35 IRow headerRow = sheet.GetRow(0);
36 int cellCount = headerRow.LastCellNum;
37 int rowCount = sheet.LastRowNum;
38
39 //循环添加标题列
40 for (int i = headerRow.FirstCellNum; i < cellCount; i++)
41 {
42 DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
43 table.Columns.Add(column);
44 }
45
46 //数据
47 for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
48 {
49 IRow row = sheet.GetRow(i);
50 DataRow dataRow = table.NewRow();
51 if (row != null)
52 {
53 for (int j = row.FirstCellNum; j < cellCount; j++)
54 {
55 if (row.GetCell(j) != null)
56 {
57 dataRow[j] = GetCellValue(row.GetCell(j));
58 }
59 }
60 }
61 table.Rows.Add(dataRow);
62 }
63 return table;
64 }
65
66 private static string GetCellValue(ICell cell)
67 {
68 if (cell == null)
69 {
70 return string.Empty;
71 }
72
73 switch (cell.CellType)
74 {
75 case CellType.Blank:
76 return string.Empty;
77 case CellType.Boolean:
78 return cell.BooleanCellValue.ToString();
79 case CellType.Error:
80 return cell.ErrorCellValue.ToString();
81 case CellType.Numeric:
82 case CellType.Unknown:
83 default:
84 return cell.ToString();
85 case CellType.String:
86 return cell.StringCellValue;
87 case CellType.Formula:
88 try
89 {
90 HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
91 e.EvaluateInCell(cell);
92 return cell.ToString();
93 }
94 catch
95 {
96 return cell.NumericCellValue.ToString();
97 }
98 }
99 }
100 }