const string fileName = "d:\aa.xlsx"; //路径 FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate); //读取文件流 HSSFWorkbook workbook = new HSSFWorkbook(fs); //根据EXCEL文件流初始化工作簿 var sheet1= workbook.GetSheetAt(0); //获取第一个sheet DataTable table = new DataTable();// var row1 = sheet1.GetRow(0);//获取第一行即标头 int cellCount = row1.LastCellNum; //第一行的列数 //把第一行的数据添加到datatable的列名 for (int i = row1.FirstCellNum; i < cellCount; i++) { DataColumn column = new DataColumn(row1.GetCell(i).StringCellValue); table.Columns.Add(column); } int rowCount = sheet1.LastRowNum; //总行数 //把每行数据添加到datatable中 for (int i = (sheet1.FirstRowNum + 1); i < sheet1.LastRowNum; i++) { HSSFRow row = sheet1.GetRow(i); DataRow dataRow = table.NewRow(); for (int j = row.FirstCellNum; j < cellCount; j++) { if (row.GetCell(j) != null) dataRow[j] = row.GetCell(j).ToString(); } table.Rows.Add(dataRow); } //到这里 table 已经可以用来做数据源使用了 workbook = null; //清空工作簿--释放资源 sheet1 = null; //清空sheet
[源码分享]NPOI读取Excel到 dataTable
最新推荐文章于 2022-06-13 16:06:39 发布