The program handles Excel using the Microsoft.Office.Interop.Excel method, which requires the computer to install Excel, and the Excel version needs to be the same, inconvenient to use. Use Npoi to install Office without a computer.
: http://npoi.codeplex.com/
Download Npoi 2.2.1 Binary Package.zip, unzip it with Net20 and NET40. I used the NET40 to add references to all the DLLs inside.
Read Excel
usingNpoi. HSSF. Usermodel;usingNpoi. Ss. Usermodel;usingNpoi. XSSF. Usermodel;usingSystem.IO;Private voidReadpatternexcel (stringFilePath,intSheetindex) {Iworkbook WorkBook=NULL; Isheet sheet; Try{FileInfo FileInfo=NewFileInfo (FilePath); if(fileinfo.exists) {FileStream fs=Fileinfo.openread (); Switch(fileinfo.extension) {//xls is 03, open with Hssfworkbook,. xlsx is 07 or 10 Open with Xssfworkbook Case ". xls": WorkBook=NewHssfworkbook (FS); Break; Case ". xlsx": WorkBook=NewXssfworkbook (FS); Break; default: Break; } fs. Close ();//Close File Stream } if(workbook!=NULL) {Sheet=Workbook.getsheetat (Sheetindex); IRow HeaderRow= Sheet. GetRow (0); intColCount = Headerrow.lastcellnum;//Number of columns//Traverse for(intI=sheet. Firstrownum;i<=sheet. lastrownum;i++) {Console.Write ("Row"+i.tostring () +" "); Npoi. Ss. Usermodel.irow Row= Sheet. GetRow (i);//get a row for(intJ=row. Firstcellnum;j<row. lastcellnum;j++) { stringdata =row. Getcell (j). ToString (); Console.Write (data); } Console.WriteLine (); } } } Catch(Exception e) {MessageBox.Show (e.message.tostring (),"Error", MessageBoxButtons.OK, Messageboxicon.error); } finally{WorkBook=NULL; Sheet=NULL; } }
C # Excel uses Npoi