/// <summary> ///query an Excel spreadsheet to add to a dataset/// </summary> /// <param name= "Filenameurl" >Server Path</param> /// <param name= "table" >Table name</param> PublicDataSet Execleds (stringFilenameurl,stringtable) { stringstrconn ="provider=microsoft.jet.oledb.4.0;"+"Data source="+ Filenameurl +"; Extended properties= ' Excel 8.0; Hdr=yes; Imex=1 '"; OleDbConnection Conn=NewOleDbConnection (strconn); Conn. Open (); DataSet DS=NewDataSet (); OleDbDataAdapter Odda=NewOleDbDataAdapter ("select * FROM [sheet1$]", conn); Odda. Fill (ds, table); returnds; }
protected voidLinkbutton3_click (Objectsender, EventArgs e) { if(Fileupload1.hasfile = =false)//HasFile used to check if FileUpload has a specified file{Response.Write ("<script>alert (' Please select Excel file ') </script>"); return;//when there is no file, return } stringIsxls = System.IO.Path.GetExtension (fileupload1.filename). ToString (). ToLower ();//System.IO.Path.GetExtension getting the file name extension if(Isxls! =". xls") {Response.Write ("<script>alert (' Can only select Excel Files ') </script>"); return;//When you select an Excel file that is not, return} SqlConnection cn=NewSqlConnection (strconn); cn. Open (); stringfilename = DateTime.Now.ToString ("YYYYMMDDHHMMSS") + Fileupload1.filename;//get execle filename datetime date function stringSavepath = Server.MapPath (("~\\updata\\") + filename);//Server.MapPath obtaining a virtual server relative pathFileupload1.saveas (Savepath);//SaveAs saves uploaded file contents on the serverDataSet ds = execleds (savepath, filename);//calling a custom methoddatarow[] Dr = ds. tables[0]. Select ();//define a DataRow array intRowsnum = ds. tables[0]. Rows.Count; if(Rowsnum = =0) {Response.Write ("<script>alert (' Excel table is empty table, no data! ') </script>");//prompt the user when the Excel table is empty } Else { for(inti =0; I < Dr. Length; i++) { stringCode = dr[i]["Code"]. ToString ();//Excel Column Name "name cannot change, otherwise it will go wrong" stringName = dr[i]["Name"]. ToString ();stringSPE = dr[i]["Specification"]. ToString (); stringSqlcheck ="Select COUNT (*) from D_pro where code= '"+ code +"' and Name= '"+ name +"'";//Check if the user existsSqlCommand sqlcmd =NewSqlCommand (Sqlcheck, CN); intCount =Convert.ToInt32 (sqlcmd. ExecuteScalar ()); if(Count <1) { stringInsertstr ="INSERT INTO D_pro (code,name,specification,par,pid) VALUES ('"+ code +"', '"+ name +")"; SqlCommand cmd=NewSqlCommand (Insertstr, CN); Try{cmd. ExecuteNonQuery (); } Catch(MembershipCreateUserException ex)//Catching exceptions{Response.Write ("<script>alert (' Import content:"+ ex. Message +"') </script>"); } } Else{Response.Write ("<script>alert (' repeat content! Prohibit import '); location= ' List.aspx' </script></script>"); Continue; }} Response.Write ("<script>alert (' excle table import succeeded! '); Location= ' List.aspx' </script>"); } CN. Close (); }
Import Excel to the database