当前位置: 移动技术网 > IT编程>开发语言>c# > C#使用NPOI上传excel

C#使用NPOI上传excel

2019年07月18日  | 移动技术网IT编程  | 我要评论

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

我使用的npoi版本是2.2.1.0版本

需要用到的命名空间

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网