首页 > 代码库 > 【转】C# Excel 导入到 Access数据库表(winForm版)
【转】C# Excel 导入到 Access数据库表(winForm版)
/// <summary> /// 获取Excel文件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "Excel文件(*.xls)|*.xls"; if (dlg.ShowDialog() == DialogResult.OK) { string filePath = dlg.FileName; this.textBox1.Text = filePath; } } /// <summary> /// 导入Excel文件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { if (textBox1.Text.Length == 0) { MessageBox.Show("请选择导入数据的Execl文件"); } else { try { OleDbConnectionStringBuilder connectStringBuilder = new OleDbConnectionStringBuilder(); connectStringBuilder.DataSource = this.textBox1.Text.Trim(); connectStringBuilder.Provider = "Microsoft.Jet.OLEDB.4.0"; connectStringBuilder.Add("Extended Properties", "Excel 8.0"); using (OleDbConnection cn = new OleDbConnection(connectStringBuilder.ConnectionString)) { DataSet ds = new DataSet(); string sql = "Select * from [Sheet1$]"; OleDbCommand cmdLiming = new OleDbCommand(sql, cn); cn.Open(); using (OleDbDataReader drLiming = cmdLiming.ExecuteReader()) { ds.Load(drLiming, LoadOption.OverwriteChanges, new string[] { "Sheet1" }); DataTable dt = ds.Tables["Sheet1"]; if (dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { //写入数据库数据 string MySql = "insert into ClientInfo values(‘"+dt.Rows[i]["姓名"].ToString()+"‘,‘"+dt.Rows[i]["姓名"].ToString() +"‘,‘0‘,‘"+dt.Rows[i]["备注"].ToString()+"‘,‘0‘,‘"+i.ToString()+"‘)"; new DataAccess().SQLExecute(MySql); } MessageBox.Show("数据导入成功!"); } else { MessageBox.Show("请检查你的Excel中是否存在数据"); } } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } /// <summary> /// 数据操作通用类 /// </summary> /// <param name="sql"></param> /// <returns></returns> public bool SQLExecute(string sql) { try { OleDbConnection conn = new OleDbConnection(CONNECT_STRING); conn.Open(); OleDbCommand comm = new OleDbCommand (); comm.Connection = conn; comm.CommandText = sql; comm.ExecuteNonQuery(); comm.Connection.Close(); conn.Close(); return true; } catch { return false; } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。