Import Excel to the database

Source: Internet
Author: User

        /// <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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.