1. Read the Excel data to the dataset
Public StaticSystem.Data.DataSet Excelsqlconnection (stringFilePathstringtableName) { stringStrcon ="Provider=Microsoft.Jet.OLEDB.4.0;Data source="+ filepath +"; Extended properties= ' Excel 8.0; Hdr=yes;imex=1 '"; OleDbConnection Excelconn=NewOleDbConnection (Strcon); Try { stringstrcom =string. Format ("SELECT * FROM [sheet1$]"); Excelconn.open (); OleDbDataAdapter mycommand=NewOleDbDataAdapter (strcom, excelconn); DataSet DS=NewDataSet (); Mycommand.fill (DS,"["+ TableName +"$]"); Excelconn.close (); returnds; } Catch{excelconn.close (); return NULL; } }
2. Write data to the database
protected voidButton2_Click (Objectsender, EventArgs e) { stringfilename =Fileupload1.filename; stringSavepath = Server.MapPath (("~/fujian/") +filename); Fileupload1.saveas (Savepath); DataSet DS=excelsqlconnection (savepath, filename); //Gridview1.datasource = ds; //Gridview1.databind ();datarow[] Dr = ds. tables[0]. Select (); for(inti =0; I < Dr. Length; i++) {SqlConnection myconn=Myconnect (); MyConn. Open (); stringtitle = dr[i]["name"]. ToString (); stringHuanxianweizhi = dr[i]["Loop Position"]. ToString (); stringQuyu = dr[i]["Area"]. ToString (); stringSQLSTR1 ="SELECT * from dbo.test where name= '"+ Quyu +"'";//Regional Intermediate Table conversionsSqlCommand myCmd1 =NewSqlCommand (SQLSTR1, myconn); SqlDataAdapter MyData=NewSqlDataAdapter (MYCMD1); DataSet my=NewDataSet (); MyData. Fill (my); Gridview1.datasource=my; Gridview1.databind (); stringQUYU1 = My. tables[0]. rows[0][0]. ToString ();; //SqlDataAdapter adapt = new SqlDataAdapter (SQLSTR1, myconn);DataSet DS1 =NewDataSet (); stringZuoluo = dr[i]["is located"]. ToString (); stringYONGTU = dr[i]["Use"]. ToString (); stringChengjiaotaoshu = dr[i]["Transactions"]. ToString (); stringJianzhumianji = dr[i]["Construction Area"]. ToString (); stringChengjiaozongjia = dr[i]["Total Prices"]. ToString (); stringDangrijunjia = dr[i]["Average Day"]. ToString (); stringChengjiaoriqi = dr[i]["Deal Date"]. ToString (); stringqitashuoming = dr[i]["Other Notes"]. ToString (); stringBankuai = dr[i]["Plate"]. ToString (); //SqlConnection myconn = Myconnect (); //myconn. Open (); stringSqlstr ="INSERT into Dbo.youweishuju (name, loop position, area, location, purpose, deal size, gross area, total price, when average price, deal date, other description, plate) VALUES ('"+ title +"', '"+ Huanxianweizhi +"', '"+ QUYU1 +"', '"+ Zuoluo +"', '"+ Yongtu +"', '"+ Chengjiaotaoshu +"', '"+ Jianzhumianji +"', '"+ Chengjiaozongjia +"', '"+ Dangrijunjia +"', '"+ Chengjiaoriqi +"', '"+ qitashuoming +"', '"+ Bankuai +"')"; //string sqlstr = "INSERT into Dbo.youweishuju (name) VALUES ('" + title + "')";SqlCommand myCMD =NewSqlCommand (Sqlstr, myconn); Mycmd.executenonquery (); MyConn. Close (); } }
Excel import data to SQL Server