C# winform 编程 向ACCESS数据库导入EXCEL表使用心得

时间:2023-03-08 17:52:28
  public string MyConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=ErLake.mdb";
/// <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;
} } private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text.Length == )
{
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 > )
{
for (int i = ; i < dt.Rows.Count; i++)
{
//写入数据库数据
// string MySql = "insert into 洱海各月出流流量 values('" + dt.Rows[i]["年"].ToString() + "','" + dt.Rows[i]["一月"].ToString()+ "','0','" + dt.Rows[i]["备注"].ToString() + "','0','" + i.ToString() + "')";
string MySql = "insert into 洱海各月出流流量 values('" + dt.Rows[i]["年"].ToString() + "','" +
dt.Rows[i]["一月"].ToString() + "','" +
dt.Rows[i]["二月"].ToString() + "','" +
dt.Rows[i]["三月"].ToString() + "','" +
dt.Rows[i]["四月"].ToString() + "','" +
dt.Rows[i]["五月"].ToString() + "','" +
dt.Rows[i]["六月"].ToString() + "','" +
dt.Rows[i]["七月"].ToString() + "','" +
dt.Rows[i]["八月"].ToString() + "','" +
dt.Rows[i]["九月"].ToString() + "','" +
dt.Rows[i]["十月"].ToString() + "','" +
dt.Rows[i]["十一月"].ToString() + "','" +
dt.Rows[i]["十二月"].ToString() + "','" +
dt.Rows[i]["全年平均"].ToString() + "')";
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(MyConnectionString);
conn.Open();
OleDbCommand comm = new OleDbCommand();
comm.Connection = conn;
comm.CommandText = sql;
comm.ExecuteNonQuery();
comm.Connection.Close();
conn.Close();
return true;
}
catch
{
return false; }
}
}

上面这段代码可以向ACCESS数据库表中导入EXCEL表,但是有个问题:导入数据后,查询数据表的数据发现新导入的数据出现在查询结果的前面,这不是我想要的,怎么办呢,我就采用字段升序排序的方式解决该问题!结果证明是有效的!

        string MySQL = "Select * from 洱海各月出流流量 order by 年 asc";