It's only in the case of MVC.
PublicActionResult Index () {varPath = Server.MapPath (@"/content/user.xlsx"); varDt= exceltodatatable (true, path); List<User> list =NewList<user>(); foreach(DataRow Iteminchdt. Rows) {list. ADD (NewUser () {No=convert.toint32 (item[0]), Name= item[1]. ToString (), age=convert.toint32 (item[2]), Sex=item[3]. ToString ()}); } returnView (list); } /// <summary> ///import data from Excel into a DataTable/// </summary> /// <param name= "Isfirstrowcolumn" >whether the first row is a column name for a DataTable</param> /// <param name= "FileName" >file path</param> /// <returns>the DataTable returned</returns> Public StaticDataTable exceltodatatable (BOOLIsfirstrowcolumn,stringfileName) { if(string. IsNullOrEmpty (FileName)) {Throw NewArgumentNullException (fileName); } vardata =NewDataTable (); Iworkbook Workbook=NULL; FileStream FS=NULL; Try{FS=NewFileStream (FileName, FileMode.Open, FileAccess.Read); if(Filename.indexof (". xlsx", stringcomparison.ordinal) >0) {Workbook=NewXssfworkbook (FS); } Else if(Filename.indexof (". xls", stringcomparison.ordinal) >0) {Workbook=NewHssfworkbook (FS); } isheet Sheet=NULL; if(Workbook! =NULL) { //get the first sheetSheet = workbook. Getsheetat (0); } if(Sheet = =NULL)returndata; varFirstRow = sheet. GetRow (0); //the number of the last cell in a row is the total number of columns intCellcount =Firstrow.lastcellnum; intStartRow; if(isfirstrowcolumn) { for(inti = Firstrow.firstcellnum; i < Cellcount; ++i) {varCell =Firstrow.getcell (i); varCellvalue =cell. Stringcellvalue; if(Cellvalue = =NULL)Continue; varColumn =NewDataColumn (Cellvalue); Data. Columns.Add (column); } StartRow= Sheet. Firstrownum +1; } Else{StartRow=sheet. Firstrownum; } //the label of the last column varRowCount =sheet. Lastrownum; for(vari = StartRow; I <= RowCount; ++i) {varrow =sheet. GetRow (i); //rows with no data default is null if(Row = =NULL)Continue; varDataRow =data. NewRow (); for(intj = row. Firstcellnum; J < Cellcount; ++j) {//Similarly, cells that do not have data are null by default if(Row. Getcell (j)! =NULL) Datarow[j]=row. Getcell (j). ToString (); } data. Rows.Add (DataRow); } returndata; } Catch(IOException ioex) {Throw NewIOException (Ioex. Message); } Catch(Exception ex) {Throw NewException (ex. Message); } finally { if(FS! =NULL) {fs. Close (); } } }
Using Npoi to read Excel table data under. Net