winform excel导入mysql_【转】C# Excel 导入到 Access数据库表(winForm版)

///

///获取Excel文件///

///

///

private void button1_Click(objectsender, EventArgs e)

{

OpenFileDialog dlg= newOpenFileDialog();

dlg.Filter= "Excel文件(*.xls)|*.xls";if (dlg.ShowDialog() ==DialogResult.OK)

{string filePath =dlg.FileName;this.textBox1.Text =filePath;

}

}///

///导入Excel文件///

///

///

private void button2_Click(objectsender, EventArgs e)

{if (textBox1.Text.Length == 0)

{

MessageBox.Show("请选择导入数据的Execl文件");

}else{try{

OleDbConnectionStringBuilder connectStringBuilder= newOleDbConnectionStringBuilder();

connectStringBuilder.DataSource= this.textBox1.Text.Trim();

connectStringBuilder.Provider= "Microsoft.Jet.OLEDB.4.0";

connectStringBuilder.Add("Extended Properties", "Excel 8.0");using (OleDbConnection cn = newOleDbConnection(connectStringBuilder.ConnectionString))

{

DataSet ds= newDataSet();string sql = "Select * from [Sheet1$]";

OleDbCommand cmdLiming= newOleDbCommand(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()+"‘)";newDataAccess().SQLExecute(MySql);

}

MessageBox.Show("数据导入成功!");

}else{

MessageBox.Show("请检查你的Excel中是否存在数据");

}

}

}

}catch(Exception ex)

{

MessageBox.Show(ex.ToString());

}

}

}///

///数据操作通用类///

///

///

public bool SQLExecute(stringsql)

{try{

OleDbConnection conn= newOleDbConnection(CONNECT_STRING);

conn.Open();

OleDbCommand comm= newOleDbCommand ();

comm.Connection=conn;

comm.CommandText=sql;

comm.ExecuteNonQuery();

comm.Connection.Close();

conn.Close();return true;

}catch{return false;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值