技术员联盟提供win764位系统下载,win10,win7,xp,装机纯净版,64位旗舰版,绿色软件,免费软件下载基地!

当前位置:主页 > 教程 > 服务器类 >

C#使用NPOI上传excel教程

来源:技术员联盟┆发布时间:2017-06-06 18:09┆点击:

  我使用的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之后就是使用事物循环插入数据库中,这个就不解释了。