C#读取Excel转为DataTable
需要的Dll: NPOI.OOXML.dll https://files.cnblogs.com/files/CityOfThousandFires/NPOI.dl.rar
/// <summary> /// Excel->DataTable /// </summary> /// <param name="filePath">Excel文件路径</param> public static DataTable ReadExcel(string filePath) { IWorkbook iwkX; using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { iwkX = WorkbookFactory.Create(fs); fs.Close(); } //sheet DataTable dt = new DataTable(); for (int h = 0; h < iwkX.NumberOfSheets; h++) { ISheet sheet = iwkX.GetSheetAt(h); var rows = sheet.GetRowEnumerator(); bool isMove = rows.MoveNext(); //循环sheet if (isMove) { var Cols = (IRow)rows.Current; dt.TableName = sheet.SheetName; for (int i = 0; i < Cols.LastCellNum; i++) { string str = Cols.GetCell(i).ToString(); dt.Columns.Add(Cols.GetCell(i).ToString()); } while (rows.MoveNext()) { var row = (IRow)rows.Current; var dr = dt.NewRow(); for (int i = 0; i < row.LastCellNum; i++) { var cell = row.GetCell(i); if (cell == null) { dr[i] = ""; } else { string strdr = cell.ToString(); dr[i] = cell.ToString(); } } dt.Rows.Add(dr); } } } return dt; }