寫本文章的目的是為了記錄工作中遇到的問題,方便以后遇到可以迅速解決問題
我使用的NPOI版本是2.2.1.0版本

需要用到的命名空間
using NPOI.HSSF.UserModel;using NPOI.SS.UserModel;using NPOI.XSSF.UserModel;
首先需要讀取excel文件中的內(nèi)容轉(zhuǎn)為表格
string path為excel表格文件的在本地的地址
Stream fs為上傳文件的流可以根據(jù)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);//第一行為標(biāo)題行 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);//添加行標(biāo)題 } 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之后就是使用事物循環(huán)插入數(shù)據(jù)庫中,這個(gè)就不解釋了。
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注