第一次写,请大家指教!!话不多说 直接走代码!
1 /// <summary> 2 /// 打开文件 3 /// </summary> 4 /// <param name="sender"></param> 5 /// <param name="e"></param> 6 private void btn_file_Click(object sender, EventArgs e) 7 { 8 OpenFileDialog openFile = new OpenFileDialog(); 9 openFile.Filter = "Execl(*.xls)|*.xls|accdb(*.accdb)|*.accdb"; 10 if (openFile.ShowDialog() == DialogResult.OK) { 11 SelectInfo(openFile.FileName); 12 } 13 }
1 /// <summary> 2 /// 读取数据 3 /// </summary> 4 /// <param name="path"></param> 5 public void SelectInfo(string path) { 6 string Suffix = Path.GetExtension(path); 7 //string tabName = "Student"; 8 string tabName = ""; //查询的表名 建议在窗体上面 加一个textbox控件 9 if (tabName.Equals("")) 10 { 11 tabName += "[sheet1$]"; 12 } 13 string strConn = string.Empty; 14 //path = Environment.CurrentDirectory; 15 switch (Suffix) 16 { 17 case ".xls": 18 strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=‘Excel 8.0;HDR=No;IMEX=1;‘"; 19 //tabName += "$"; 20 break; 21 case ".xlsx": 22 strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=‘Excel 8.0;HDR=False;IMEX=1‘"; 23 // tabName += "$"; 24 break; 25 case ".mdb": 26 strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path; 27 break; 28 case ".accdb"://Access2007 29 strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+path; 30 break; 31 default: 32 break; 33 } 34 OleDbConnection oledbConn = new OleDbConnection(strConn); 35 try 36 { 37 // oledbConn.Open(); 38 string sql = "Select * from " + tabName; 39 OleDbDataAdapter oledbDa = new OleDbDataAdapter(sql, oledbConn); 40 DataSet ds = new DataSet(); 41 oledbDa.Fill(ds,"信息"); 42 this.dgv_Info.DataSource = ds.Tables["信息"]; 43 } 44 catch (Exception) 45 { 46 47 throw; 48 } 49 finally { 50 oledbConn.Close(); 51 } 52 }
运行效果:
适合初学者。第一次写,大神不要吐槽呀。。。。