Excel 批量快速导入mySQL 解决方案~~

  
    
1 最近在做一个交叉表的数据批量导入,采用过很多方式一直没有特别理想的解决方案,昨天终于解决了,以下是测试记录:
2
3 OpenFileDialog openfile = new OpenFileDialog();
4 openfile.Filter = " 工作薄(*.xlsx)|*.xlsx|所有文件(*.*)|*.* " ;
5 if (openfile.FilterIndex == 1 && openfile.ShowDialog() == DialogResult.OK)
6 {
7 string path = openfile.FileName;
8 string strConn = " Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " + path + " ;Extended Properties=\"Excel 12.0;HDR=YES\" " ;
9 System.Data.OleDb.OleDbConnection oleConn = new System.Data.OleDb.OleDbConnection(strConn);
10 oleConn.Open();
11 System.Data.OleDb.OleDbDataAdapter oleDa = new System.Data.OleDb.OleDbDataAdapter( " select * from [sheet1$] " , oleConn);
12 DataSet ds = new DataSet();
13 oleDa.Fill(ds);
14 strConn.Clone();
15 dgvJjList.DataSource = ds.Tables[ 0 ];
16 }
17
18 this .backgroundWorker1.RunWorkerAsync();
19
20 数据导入:分为两个步骤:第一、先把数据从EXCEL导入到DataGridView;第二、启动后台处理线程。
21
22 在线程中同步更新UI控件:
23
24 public delegate void MyInvoke( string str);
25
26 delegate void Starttqdata();
27
28 public void SetTxt( string str)
29 {
30 textBox2.Visible = true ;
31 textBox2.Text = " 正在导入 " + str.ToString() + " 条数据. " ;
32 }
33
34 /// /
35
36 GetDataGridView()
37
38 {
39
40 /// /DataGridView数据绑定
41
42 }
43
44 /// /
45
46 在线程中调用:
47
48 MyInvoke mi = new MyInvoke(SetTxt);
49 BeginInvoke(mi, new object [] { row.Index.ToString() });
50
51 this .Invoke( new Starttqdata(GetDataGridView));
52
53 后台线程处理:
54
55 一种方式:
56
57 1 、先把数据全部插入到一个临时表中,和你导入的目标表相同的表结构
58
59 2 、然后利用Load data OutFile到一个 * .txt文本文件中
60
61 3 、利用Load data Infile * .txt到目标数据表中
62
63 另外一种方式:
64
65 1 、先把数据全部插入到一个临时表中,和你导入的目标表相同的表结构
66
67 2 、将临时表数据导入到目标数据表中,当然要判断是否有该记录,如有更新,没有插入,呵呵,没有load data Infile Replace方便了。
68
69 10W条数据在10s - 20s之间,应该还是在可承受范围之内。当然更为合适的方式就是导入数据的excel格式与你的目标表格式相同,那就执行效率更高了,20W条数据只需要几s就搞定了。

你可能感兴趣的:(mysql)