C# 读取Execl和Access数据库

时间:2021-10-30 13:26:30

第一次写,请大家指教!!话不多说 直接走代码!

         /// <summary>
/// 打开文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_file_Click(object sender, EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "Execl(*.xls)|*.xls|accdb(*.accdb)|*.accdb";
if (openFile.ShowDialog() == DialogResult.OK) {
SelectInfo(openFile.FileName);
}
}
 /// <summary>
/// 读取数据
/// </summary>
/// <param name="path"></param>
public void SelectInfo(string path) {
string Suffix = Path.GetExtension(path);
//string tabName = "Student";
string tabName = ""; //查询的表名 建议在窗体上面 加一个textbox控件
if (tabName.Equals(""))
{
tabName += "[sheet1$]";
}
string strConn = string.Empty;
//path = Environment.CurrentDirectory;
switch (Suffix)
{
case ".xls":
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=No;IMEX=1;'";
//tabName += "$";
break;
case ".xlsx":
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
// tabName += "$";
break;
case ".mdb":
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path;
break;
case ".accdb"://Access2007
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+path;
break;
default:
break;
}
OleDbConnection oledbConn = new OleDbConnection(strConn);
try
{
// oledbConn.Open();
string sql = "Select * from " + tabName;
OleDbDataAdapter oledbDa = new OleDbDataAdapter(sql, oledbConn);
DataSet ds = new DataSet();
oledbDa.Fill(ds,"信息");
this.dgv_Info.DataSource = ds.Tables["信息"];
}
catch (Exception)
{ throw;
}
finally {
oledbConn.Close();
}
}

运行效果:C# 读取Execl和Access数据库

适合初学者。第一次写,大神不要吐槽呀。。。。