Use NPOI to upload excel and npoi to upload excel
The purpose of this article is to record problems encountered in the work, so that problems can be solved quickly in the future.
The NPOI version I use is 2.2.1.0.
Namespace to be used
using NPOI.HSSF.UserModel;using NPOI.SS.UserModel;using NPOI.XSSF.UserModel;
First, you must read the content in the excel file and convert it into a table.
String path is the local address of the excel file.
Stream fs is the Stream for uploading Files, which can be obtained according to 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 version 2003} ISheet sheet = workbook. getSheetAt (0); // get the first DataTable table = new DataTable (); IRow headerRow = sheet. getRow (0); // The first row title line int cellCount = header Row. 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); // Add row title} 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 ;}
After dateTable is obtained, it is inserted into the database using a transaction loop. This is not explained.