码迷,mamicode.com
首页 > 数据库 > 详细

Excel数据直接到DataTable--->DB

时间:2018-03-21 14:10:13      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:message   初始   else   定义函数   sync   RKE   mat   +=   use   

1) Excel数据直接导入到临时生成的DataTable

技术分享图片
 using (OleDbConnection selectConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;data source=" + filePath + ";Extended Properties=‘Excel 12.0;HDR=Yes;IMEX=1‘"))
            {
                selectConnection.Open();
                OleDbDataAdapter adapter = new OleDbDataAdapter("select * from [hr$]", selectConnection);
                //adapter.Fill(dataset);
                adapter.Fill(dt);
            }
View Code

2) 启动线程 ,触发 DoWork事件
       bgwInsertData.RunWorkerAsync();

3) 程序初始化   

技术分享图片
    public Form1()
        {
            InitializeComponent();
            //设置进度条自动更新数据
            bgwInsertData.WorkerReportsProgress = true;
            bgwInsertData.WorkerSupportsCancellation = true;

            bgwInsertData.DoWork += new DoWorkEventHandler(bgwInsertData_DoWork);
            bgwInsertData.ProgressChanged += new ProgressChangedEventHandler(bgwInsertData_ProgressChanged);
            bgwInsertData.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgwInsertData_RunWorkerCompleted);

        }
View Code

4) 进度条处理代码

技术分享图片
void bgwInsertData_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if (e.Cancelled)
            {
                MessageBox.Show("取消操作!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                //加固
                if (progressBar1.Value <= 0)
                {
                    return;
                }
                //绑定数据 数据呈现
                dgv.AllowUserToAddRows = false;
                dgv.DataSource = dt;             
            }
        }

        void bgwInsertData_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            lblResult.Text = "已获取数据" + e.ProgressPercentage.ToString() + "%";
        }

        void bgwInsertData_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            //2.在DoWork中调用自定义函数,并将引发DoWork事件的sender传递出去
            insertData(worker);  
        }
View Code

5)实现效果
     技术分享图片

6) 涉及到知识点:Excel数据直接导入DB,线程(进度条)。

 

Excel数据直接到DataTable--->DB

标签:message   初始   else   定义函数   sync   RKE   mat   +=   use   

原文地址:https://www.cnblogs.com/senlinzhang/p/8616030.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!