软件编程
位置:首页>> 软件编程>> C#编程>> C#使用NPOI上传excel

C#使用NPOI上传excel

作者:勤奋的小鑫0  发布时间:2022-05-20 14:46:22 

标签:C#,NPOI,excel

写本文章的目的是为了记录工作中遇到的问题,方便以后遇到可以迅速解决问题

我使用的NPOI版本是2.2.1.0版本

C#使用NPOI上传excel

需要用到的命名空间


using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

首先需要读取excel文件中的内容转为表格

string path为excel表格文件的在本地的地址

Stream fs为上传文件的流可以根据Request.Files[0].InputStream  获得


public DataTable GetexcelDataSet(string path, Stream fs)
 {
  IWorkbook workbook = null;
  if (path.IndexOf(".xlsx") > 0)
  {
   workbook = new XSSFWorkbook(fs);//excel的版本2007
  }
  else if (path.IndexOf(".xls") > 0)
  {
   workbook = new HSSFWorkbook(fs);//excel的版本2003
  }
  ISheet sheet = workbook.GetSheetAt(0);//得到第一张表
  DataTable table = new DataTable();
  IRow headerRow = sheet.GetRow(0);//第一行为标题行
  int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
  int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1

for (int i = headerRow.FirstCellNum; i < cellCount; i++)
  {
   DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
   table.Columns.Add(column);//添加行标题
  }
  for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
  {
   IRow row = sheet.GetRow(i);
   DataRow dataRow = table.NewRow();
   if (row != null)
   {
    for (int j = row.FirstCellNum; j < cellCount; j++)
    {
     if (row.GetCell(j) != null)
      dataRow[j] = row.GetCell(j);

}
   }
   table.Rows.Add(dataRow);
  }
  return table;
 }

得到dateTable之后就是使用事物循环插入数据库中,这个就不解释了。

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com