Get the Excel file path first through control FileUpload
protected voidBtnreadexcelfromfileupload_click (Objectsender, EventArgs e) { if(FupExcel.PostedFile.ContentLength >0) { //Get full path stringFullfilename =fupExcel.PostedFile.FileName.ToString (); //Get file name stringFileName =fupExcel.FileName.ToString (); //Get file Type stringType = filename.substring (Filename.lastindexof (".") +1); //Get upload path stringPath = Server.MapPath ("uploadfile\\")+FileName; Response.Write (path); //File SizeFileInfo file =NewFileInfo (fullfilename); floatsize= (file. length/1024x768)/1024x768; if(Type! ="xls") {Response.Write ("<script language= ' javascript ' >alert (' not an Excel file! ') </script>"); } Else { //fupExcel.PostedFile.SaveAs (path);//Upload to ServerDataSet ds =Importexcel (fullfilename); Gvfirst.datasource=ds; Gvfirst.databind (); } } }
Read the data in the Excel file into the dataset
/// <summary> ///reading Excel data to a dataset/// </summary> /// <param name= "filename" ></param> /// <returns></returns> PublicDataSet Importexcel (stringfilename) { //file path stringExcelname =filename; //Hdr=yes has two values: yes/no, indicates whether the first row is a field name, the default is yes, the first row is the field name /*The IMEX has three values 0,1,2, and the other two values indicate what, when imex=0 is the "Export mode", the Excel file opened by this mode can only be used for "write" purposes. When Imex=1 is "Import Mode", the Excel file opened in this mode can only be used for "read" purposes. When imex=2 is "connected mode", the Excel file opened in this mode can support both "read" and "write" purposes. See:http://www.cnblogs.com/goto/archive/2012/04/12/2443670.html */ stringStrcon ="Provider=Microsoft.Jet.OLEDB.4.0;Data source="+ Excelname +"; Extended properties= ' Excel 8.0; Hdr=no;imex=1 ';";//a string that connects to an Excel file if(Excelname = =NULL) { return NULL; } OleDbConnection Odcon=NewOleDbConnection (Strcon);//Establish a connectionOdcon. Open ();//Open ConnectionSystem.Data.DataTable sTable = Odcon. GetOleDbSchemaTable (System.Data.OleDb.OleDbSchemaGuid.Tables,NULL); //Sheets Name stringTableName = stable.rows[0][2]. ToString (). Trim (); if(TableName = ="") { return NULL; } Else{tableName="["+ TableName +"]"; } OleDbDataAdapter Odda=NewOleDbDataAdapter ("SELECT * from"+TableName, Odcon); DataSet DS=NewDataSet (); Try{Odda. Fill (DS); } Catch(Exception ex) {Clientscript.registerstartupscript ( This. Page.gettype (),"","<script language= ' javascript ' Defer>alert ('"+ex. Message+"');</script>"); } returnds; }
ASP. NET read Excel data