这篇文章主要介绍了C#中怎么使用NPOI读取excel转为DataSet的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇C#中怎么使用NPOI读取excel转为DataSet文章都会有所收获,下面我们一起来看看吧。

NPOI读取excel转为DataSet

///<summary>///读取Execl数据到DataTable(DataSet)中///</summary>///<paramname="filePath">指定Execl文件路径</param>///<paramname="isFirstLineColumnName">设置第一行是否是列名</param>///<returns>返回一个DataTable数据集</returns>publicstaticDataSetExcelToDataSet(stringfilePath,boolisFirstLineColumnName){DataSetdataSet=newDataSet();intstartRow=0;try{using(FileStreamfs=File.OpenRead(filePath)){IWorkbookworkbook=null;//如果是2007+的Excel版本if(filePath.IndexOf(".xlsx")>0){workbook=newXSSFWorkbook(fs);}//如果是2003-的Excel版本elseif(filePath.IndexOf(".xls")>0){workbook=newHSSFWorkbook(fs);}if(workbook!=null){//循环读取Excel的每个sheet,每个sheet页都转换为一个DataTable,并放在DataSet中for(intp=0;p<workbook.NumberOfSheets;p++){ISheetsheet=workbook.GetSheetAt(p);DataTabledataTable=newDataTable();dataTable.TableName=sheet.SheetName;if(sheet!=null){introwCount=sheet.LastRowNum;//获取总行数if(rowCount>0){IRowfirstRow=sheet.GetRow(0);//获取第一行intcellCount=firstRow.LastCellNum;//获取总列数//构建datatable的列if(isFirstLineColumnName){startRow=1;//如果第一行是列名,则从第二行开始读取for(inti=firstRow.FirstCellNum;i<cellCount;++i){ICellcell=firstRow.GetCell(i);if(cell!=null){if(cell.StringCellValue!=null){DataColumncolumn=newDataColumn(cell.StringCellValue);dataTable.Columns.Add(column);}}}}else{for(inti=firstRow.FirstCellNum;i<cellCount;++i){DataColumncolumn=newDataColumn("column"+(i+1));dataTable.Columns.Add(column);}}//填充行for(inti=startRow;i<=rowCount;++i){IRowrow=sheet.GetRow(i);if(row==null)continue;DataRowdataRow=dataTable.NewRow();for(intj=row.FirstCellNum;j<cellCount;++j){ICellcell=row.GetCell(j);if(cell==null){dataRow[j]="";}else{//CellType(Unknown=-1,Numeric=0,String=1,Formula=2,Blank=3,Boolean=4,Error=5,)switch(cell.CellType){caseCellType.Blank:dataRow[j]="";break;caseCellType.Numeric:shortformat=cell.CellStyle.DataFormat;//对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理if(format==14||format==22||format==31||format==57||format==58)dataRow[j]=cell.DateCellValue;elsedataRow[j]=cell.NumericCellValue;break;caseCellType.String:dataRow[j]=cell.StringCellValue;break;}}}dataTable.Rows.Add(dataRow);}}}dataSet.Tables.Add(dataTable);}}}returndataSet;}catch(Exceptionex){varmsg=ex.Message;returnnull;}}

Dataset 导出为Excel

///<summary>///将DataTable(DataSet)导出到Execl文档///</summary>///<paramname="dataSet">传入一个DataSet</param>///<paramname="Outpath">导出路径(可以不加扩展名,不加默认为.xls)</param>///<returns>返回一个Bool类型的值,表示是否导出成功</returns>///True表示导出成功,Flase表示导出失败publicstaticboolDataTableToExcel(DataSetdataSet,stringOutpath){boolresult=false;try{if(dataSet==null||dataSet.Tables==null||dataSet.Tables.Count==0||string.IsNullOrEmpty(Outpath))thrownewException("输入的DataSet或路径异常");intsheetIndex=0;//根据输出路径的扩展名判断workbook的实例类型IWorkbookworkbook=null;stringpathExtensionName=Outpath.Trim().Substring(Outpath.Length-5);if(pathExtensionName.Contains(".xlsx")){workbook=newXSSFWorkbook();}elseif(pathExtensionName.Contains(".xls")){workbook=newHSSFWorkbook();}else{Outpath=Outpath.Trim()+".xls";workbook=newHSSFWorkbook();}//将DataSet导出为Excelforeach(DataTabledtindataSet.Tables){sheetIndex++;if(dt!=null&&dt.Rows.Count>0){ISheetsheet=workbook.CreateSheet(string.IsNullOrEmpty(dt.TableName)?("sheet"+sheetIndex):dt.TableName);//创建一个名称为Sheet0的表introwCount=dt.Rows.Count;//行数intcolumnCount=dt.Columns.Count;//列数//设置列头IRowrow=sheet.CreateRow(0);//excel第一行设为列头for(intc=0;c<columnCount;c++){ICellcell=row.CreateCell(c);cell.SetCellValue(dt.Columns[c].ColumnName);}//设置每行每列的单元格,for(inti=0;i<rowCount;i++){row=sheet.CreateRow(i+1);for(intj=0;j<columnCount;j++){ICellcell=row.CreateCell(j);//excel第二行开始写入数据cell.SetCellValue(dt.Rows[i][j].ToString());}}}}//向outPath输出数据using(FileStreamfs=File.OpenWrite(Outpath)){workbook.Write(fs);//向打开的这个xls文件中写入数据result=true;}returnresult;}catch(Exceptionex){returnfalse;}}}

调用方法

DataSetset=ExcelHelper.ExcelToDataTable("test.xlsx",true);//Excel导入boolb=ExcelHelper.DataTableToExcel(set,"test2.xlsx");//导出Excel

关于“C#中怎么使用NPOI读取excel转为DataSet”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“C#中怎么使用NPOI读取excel转为DataSet”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。