1. Create a WinForm program and add a button control
2.Button Events
Private void button1_click (object sender, EventArgs e) { new OpenFileDialog (); if (FD. ShowDialog () = = DialogResult.OK ) {string fileName = FD. FileName; Syncexceltodatabase (FileName, textBox1.Text.ToString ()); } }
3. Reading data from Excel to a DataTable
Private voidSyncexceltodatabase (stringExcelfilepath,stringsheetname) { stringstrconn ="Provider=microsoft.ace.oledb.12.0;data source="+ Excelfilepath +";"+"Extended properties= ' Excel 12.0; HDR = Yes '"; stringStrexcel =string. Format ("SELECT * FROM [{0}$]", SheetName); OleDbDataAdapter da=NewOleDbDataAdapter (Strexcel, strconn); DataSet DS=NewDataSet (); Try{da. Fill (DS); DT= ds. tables[0]; if(dt! =NULL&& dt. Rows.Count >0) { foreach(DataRow Drinchdt. Rows) {Update (DR); } } } Catch(Exception err) {MessageBox.Show ("operation failed! "+Err. ToString ()); } }
4. Updating to a SQL Server database
Private voidUpdate (DataRow dr) {stringSalename = dr["telesales MANILA"]. ToString (). Trim (); stringCRN = dr["CRN"]. ToString (). Trim (); if(!string. IsNullOrEmpty (salename) && salename! ="#N /A") { string[] arr = Salename.split (' '); if(arr.) Length>0) { stringSQL1 ="SELECT *from [dbo]. [Puseradmin] where firstname= '"+ arr[0] +"' and Lastname= '"+ arr[1] +"'"; DataTable Dtresult=sqlhelper.executedatatable (Sql1,commandtype.text); stringSQL2 ="Update [dbo]. [pagents] Set bfax= '"+ dtresult.rows[0][0] +"' where crn= '"+ CRN +"'"; Sqlhelper.executenonquery (SQL2, CommandType.Text); } } }
Simple synchronization of Excel data into SQL Server database