Npoi is to operate the Excel file as a binary stream, and also write the binary stream file into the Excel file format 1. write Excel Hssfworkbook WorkBook = new Hssfworkbook (); Isheet sheet = workbook.createsheet ("Employee table"); IRow Rowheader = sheet. CreateRow (0);//table header Rowheader.createcell (0, celltype.string). Setcellvalue ("work number"); Rowheader.createcell (1, celltype.string). Setcellvalue ("name"); Rowheader.createcell (2, celltype.string). Setcellvalue ("gender"); Rowheader.createcell (3, celltype.string). Setcellvalue ("Birthday"); using (Stream stream = File.openwrite (fileName)) {workbook.write (stream); }2. read Excel FileStream file = new FileStream (Server.MapPath (@ "Temfiles\tem.xls"), FileMode.Open, FileAccess.Read); Creates a hssfworkbook from an existing Excel based on the path, that is, the entire Excel document Hssfworkbook workbook = new Hssfworkbook (file); Gets the first sheet of Excel hssfsheet sheet = workbook. Getsheetat (0); DataTable table = new DataTable (); Get the first line of sheet Hssfrow headErrow = sheet. GetRow (0); The number of the last square of a row is the total number of columns int cellcount = Headerrow.lastcellnum; for (int i = headerrow.firstcellnum; i < Cellcount; i++) {DataColumn column = new DataColumn (heade Rrow.getcell (i). Stringcellvalue); Table. Columns.Add (column); }//The label of the last column is the total number of rows int rowCount = sheet. Lastrownum; for (int i = (sheet. Firstrownum + 1); I < sheet. Lastrownum; i++) {Hssfrow row = sheet. GetRow (i); if (row== null)//This sentence is critical because rows with no data default to null {continue; } DataRow datarow = table. NewRow (); for (int j = row. Firstcellnum; J < Cellcount; J + +) {if (row. Getcell (j) = null)//In the same vein, cells with no data default to null Datarow[j] = row. Getcell (j). ToString (); } table. Rows.Add (DataRow); } workbook = null; sheet = null;
Npoi about Excel and database table conversions