Simple synchronization of Excel data into SQL Server database

Source: Internet
Author: User

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

Related Article

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.