C# NPOI excel文件转datatable
using NPOI.SS.UserModel; using NPOI.XSSF.UserModel;
public DataTable ExcelToDataTable(string excelPath) { IWorkbook workbook; using (FileStream stream = new FileStream(excelPath, FileMode.Open, FileAccess.Read)) { workbook = new XSSFWorkbook(stream); } ISheet sheet = workbook.GetSheetAt(0); // zero-based index of your target sheet DataTable dt = new DataTable(sheet.SheetName); // write header row IRow headerRow = sheet.GetRow(0); foreach (ICell headerCell in headerRow) { dt.Columns.Add(headerCell.ToString()); } // write the rest int rowIndex = 0; foreach (IRow row in sheet) { // skip header row if (rowIndex++ == 0) continue; DataRow dataRow = dt.NewRow(); dataRow.ItemArray = row.Cells.Select(c => c.ToString()).ToArray(); dt.Rows.Add(dataRow); } return dt; }
NPOI下载地址:点击下载