好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C#使用NPOI上传excel

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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

dy("nrwz");

查看更多关于C#使用NPOI上传excel的详细内容...

  阅读:44次