|
楼主 |
发表于 2015-12-22 18:43
|
显示全部楼层
以下代码运行时仍出错:
- private void button2_Click(object sender, EventArgs e)
- {
- string accessFilePath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\数据源\省市区三级联动.mdb";
- object o = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
- Microsoft.Office.Interop.Excel._Application app = o as Microsoft.Office.Interop.Excel._Application;
- Microsoft.Office.Interop.Excel.Workbook srcbook = app.ActiveWorkbook;//得到当前活动的excel文档
- Microsoft.Office.Interop.Excel.Worksheet sh = (Microsoft.Office.Interop.Excel.Worksheet)srcbook.ActiveSheet;//得到当前Sheet
- try
- {
- OleDbConnectionStringBuilder connectStringBuilder = new OleDbConnectionStringBuilder();
- connectStringBuilder.DataSource = srcbook.FullName;
- connectStringBuilder.Provider = "Microsoft.Ace.OleDb.12.0";
- connectStringBuilder.Add("Extended Properties", "Excel 12.0");
- using (OleDbConnection cn = new OleDbConnection(connectStringBuilder.ConnectionString))
- {
- DataSet ds = new DataSet();
- string sql = "Select * from [" +sh.Name + "$]";
- OleDbCommand cmdLiming = new OleDbCommand(sql, cn);
- cn.Open();
- using (OleDbDataReader drLiming = cmdLiming.ExecuteReader())
- {
- ds.Load(drLiming, LoadOption.OverwriteChanges, new string[] { sh.Name });
- DataTable dt = ds.Tables[sh.Name];
- if (dt.Rows.Count > 0)
- {
- for (int i = 0; i < dt.Rows.Count; i++)
- {
- //写入数据库数据
- string MySql = "insert into VBA实现省市区三级联动(省,市,区) values('" + dt.Rows[i]["省"].ToString() + "','" + dt.Rows[i]["市"].ToString() + "','" + dt.Rows[i]["区"].ToString() + "')";
- OleDbConnection connct = new OleDbConnection();
- string oleDB = "Provider=Microsoft.Ace.OleDb.12.0;Data Source=" + accessFilePath;
- connct.ConnectionString = oleDB;
- //打开数据库
- connct.Open();
- OleDbCommand command = new OleDbCommand(sql, cn);
- command.Connection = connct;
- int res = command.ExecuteNonQuery();
- // 关闭连接
- connct.Close();
- //return res;
- }
- MessageBox.Show("数据导入成功!");
- }
- else
- {
- MessageBox.Show("请检查你的Excel中是否存在数据");
- }
- }
- }
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
复制代码 |
|