Preface
Asp.net Excel operations are already an old topic, but the npoi Excel operation I mentioned below should be one of the best solutions,Npoi can help developers read and write 97-2003 office files without installing Microsoft Office. Supported file formats include xls, Doc, and PPT. Npoi is built on poi 3.x. It can read and write word/Excel documents without installing office.
Method
Go to the official website: http://npoi.codeplex.com/download unzip import DLL (you can select. net2.0 or.Net4.0 DLL), and then add references to the website.
ExportCode:
Npoi. hssf. usermodel. hssfworkbook book = New Npoi. hssf. usermodel. hssfworkbook (); npoi. Ss. usermodel. isheet Sheet = Book. createsheet ( " Test_01 " ); // First column Npoi. Ss. usermodel. irow ROW = sheet. createrow ( 0 ); Row. createcell ( 0 ). Setcellvalue ( " The first row of the first column " ); // Column 2 Npoi. Ss. usermodel. irow row2 = sheet. createrow ( 1 ); Row2.createcell ( 0 ). Setcellvalue ( " The first row of the second column " ); // ... // Write to client System. Io. memorystream MS = New System. Io. memorystream (); book. Write (MS); response. addheader ( " Content-Disposition " ,String . Format ( " Attachment; filename%%0%.xls " , Datetime. Now. tostring ( " Yyyymmddhhmmssfff " ); Response. binarywrite (Ms. toarray (); book = Null ; Ms. Close (); Ms. Dispose ();
Import code:
Hssfworkbook; # Region Public Datatable importexcelfile ( String Filepath ){ # Region // Initialization information Try { Using (Filestream file = New Filestream (filepath, filemode. Open, fileaccess. Read) {hssfworkbook = New Hssfworkbook (File );}} Catch (Exception e ){ Throw E ;} # Endregion Npoi. Ss. usermodel. Sheet = Hssfworkbook. getsheetat ( 0 ); System. Collections. ienumerator rows = Sheet. getrowenumerator (); datatable dt = New Datatable (); For ( Int J = 0 ; J <(sheet. getrow ( 0 ). Lastcellnum); j ++ ) {DT. Columns. Add (convert. tochar ((( Int ) ' A ' ) + J). tostring ());} While (Rows. movenext () {hssfrow row = (Hssfrow) rows. Current; datarow Dr =DT. newrow (); For ( Int I = 0 ; I <row. lastcellnum; I ++ ) {Npoi. Ss. usermodel. Cell cell = Row. getcell (I ); If (Cell = Null ) {Dr [I] = Null ;} Else {Dr [I] = Cell. tostring () ;}} DT. Rows. Add (DR );} Return DT ;} # Endregion
Conclusion
This makes it easy to solve the Excel operation. You can try it. It is very useful. If you think it is useful to you, please recommend it. Thank you.