• 简单的将Excel数据同步到SqlServer数据库中


    1.创建一个WinForm程序,添加一个Button控件

    2.Button事件

     private void button1_Click(object sender, EventArgs e)
            {
                System.Windows.Forms.OpenFileDialog fd = new OpenFileDialog();
                if (fd.ShowDialog() == DialogResult.OK)
                {
                    string fileName = fd.FileName;
                    syncExcelToDataBase(fileName, textBox1.Text.ToString());
                }
            }

    3.从Excel读取数据到DataTable

           private void syncExcelToDataBase(string excelfilepath, string sheetName)
            {
                string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelfilepath + ";" + "Extended Properties='Excel 12.0; HDR = Yes'";
                string strExcel = string.Format("select * from [{0}$]", sheetName);
                OleDbDataAdapter da = new OleDbDataAdapter(strExcel, strConn);
                DataSet ds = new DataSet();
                try
                {
                    da.Fill(ds);
                    dt = ds.Tables[0];
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            Update(dr);
                        }
                    }
    
                }
                catch (Exception err)
                {
                    MessageBox.Show("操作失败!" + err.ToString());
                }
            }

    4.更新到Sql server 数据库中

            private void Update(DataRow dr)
            { 
                string saleName = dr["TELESALES MANILA"].ToString().Trim();
                string crn = dr["CRN"].ToString().Trim();
                if(!string.IsNullOrEmpty(saleName) && saleName != "#N/A")
                {
                    string[] arr = saleName.Split(' ');
                    if(arr.Length>0)
                    {
                        string sql1 = "SELECT *FROM [dbo].[PUserAdmin] where FirstName='" + arr[0] + "' and LastName='" + arr[1] + "'";
                        DataTable dtResult = SqlHelper.ExecuteDataTable(sql1,CommandType.Text);
                            string sql2 = "update [dbo].[PAgents] set BFax='" + dtResult.Rows[0][0] + "' where CRN='" + crn + "'";
                            SqlHelper.ExecuteNonQuery(sql2, CommandType.Text);
                    }
                }
            }
  • 相关阅读:
    快速排序和随机化快排学习
    P1330 封锁阳光大学 DFS
    P2577 [ZJOI2005]午餐 状压DP
    M. Subsequence 南昌邀请赛
    P1441 砝码称重 DFS回溯+DP
    P2661 信息传递 二分图的最小环
    P1196 [NOI2002]银河英雄传说 带权并查集
    P2024 [NOI2001]食物链 并查集
    F. Shovels Shop 背包DP
    P1514 引水入城 DFS
  • 原文地址:https://www.cnblogs.com/yixuanhan/p/9234432.html
Copyright © 2020-2023  润新知