C # helper code for Npoi
1 Public Static voidWriteexcel (DataTable DT,stringFilePath)2 {3 if(!string. IsNullOrEmpty (FilePath) && dt. Rows.Count >0)4 {5Hssfworkbook wk =NewHssfworkbook ();6Isheet sheet =wk. Createsheet (dt. TableName);7 8 //column Header9IRow HeaderRow = sheet. CreateRow (0);Ten for(inti =0; i < dt. Columns.count; i++) One { A Headerrow.createcell (i). Setcellvalue (dt. Columns[i]. ColumnName); - } - the //Populating content - for(inti =0; i < dt. Rows.Count; i++)//Note the condition dt. Rows.Count - { -IRow row = sheet. CreateRow (i+1); + for(intj =0; J < dt. Columns.count; J + +)//Note the condition dt. Columns.count - { +Row. Createcell (j). Setcellvalue (convert.tostring (dt. ROWS[I][J]));//Note the wording here . A } at } - //Write to client - using(MemoryStream ms =NewMemoryStream ()) - { - wk. Write (MS); - using(FileStream file =NewFileStream (FilePath, FileMode.Create, FileAccess.Write)) in { - byte[] data =Ms. ToArray (); toFile. Write (data,0, data. Length); + file. Flush (); - } theWK =NULL; * } $ Panax Notoginseng } -}View Code
Using Npoi from database to Excel