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

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,线程(进度条)。

 

posted @ 2018-03-21 11:30  森林长  阅读(667)  评论(0编辑  收藏  举报