首先拖个TextBox和一个button,也就是浏览,假设为textbox1,和button1吧
private string name = "";//文件名
private string dire = "";//文件路径前缀
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "EXCEL文件|*.xls";
open.FilterIndex = 1;
if (open.ShowDialog() == DialogResult.OK)
{
textBox1.Text = open.FileName;
name = Path.GetFileName(textBox1.Text);//这边引用using System.IO;
dire = Path.GetDirectoryName(textBox1.Text);
dire = dire.EndsWith("\\") ? dire.Substring(0, dire.Length - 1) : dire;
}
}
上面浏览就完成了,下面就是导入了,在拖个button,假设为button2
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim() == "")
{
MessageBox.Show("请填写路径!");
return;
}
OleDbConnection conn = “你的ACCESS数据库地址”;
OleDbConnection conn_Excel = new OleDbConnection ("Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Database Password=;Extended properties=Excel 5.0;Data Source=" + textBox1.Text);
OleDbTransaction tran = null;
try
{
//查出EXCEL放入DataTable
conn_Excel.Open();
string sql = "select * from [Sheet1$]";
DataTable dt = new DataTable();
OleDbDataAdapter sda = new OleDbDataAdapter(sql, conn_Excel);
sda.Fill(dt);
if (dt == null)
{
MessageBox.Show("您导入的文档名字有误!请去掉空格或特殊字符!");
return;
}
//去掉空行
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i][0].ToString().Trim() == string.Empty)
{
dt.Rows.Remove(dt.Rows[i--]);
}
}
//开始事务
tran = conn.BeginTransaction();
OleDbCommand cmd = conn.CreateCommand();
cmd.Transaction = tran;
for (int i = 0; i < dt.Rows.Count; i++)
{
string sql_insert="insert into 表名 (字段1,字段2..) values ('{0}','{1}'...)";
sql_insert = string.Format(sql_insert, dt.Rows[i][0].ToString(), dt.Rows[i][1].ToString() ....);
cmd.CommandText = sql_insert;
cmd.ExecuteNonQuery();
}
tran.Commit();//提交事务
MessageBox.Show("导入成功!");
}
catch
{
MessageBox.Show("导入失败!");
tran.Rollback();
}
finally
{
conn.Dispose();
conn_Excel.Dispose();
}
}
这个够详细了吧,不懂的在问
上传的方式?