寫本文章的目的是為了記錄工作中遇到的問題,方便以后遇到可以迅速解決問題
我使用的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之后就是使用事物循環插入數據庫中,這個就不解釋了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答