這是我第一次在博客上寫東西,簡單的爲你們分享一個oledb讀取文件的功能吧,這兩天在作一個文件導入數據庫的小demo,就想着導入前先在頁面上展現一下,以前調用Microsoft.Office.Interop.*.dll的組件,代碼看起來非常冗餘,因而乎選擇了這種方式,添加引用 using System.Data.OleDb;代碼分享給你們,有什麼不足或補充,但願你們多多發言,共同進步哈!數據庫
/// <summary> /// 使用OLEDB讀取excel和csv文件 /// </summary> /// <param name="path">文件所在目錄地址</param> /// <param name="name">文件名</param> /// <returns></returns> public static DataSet ReadFile(string path, string name) { if (string.IsNullOrWhiteSpace(path) || string.IsNullOrWhiteSpace(name) || !File.Exists(path+name)) return null; // 讀取excel string connstring = string.Empty; string strSql = string.Empty; if (name.EndsWith(".xls") || name.EndsWith(".xlsx")) { connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + name + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1';"; strSql = "select * from [sheet1$]"; } // 讀取csv文件 else if (name.EndsWith(".csv")) { connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='text;HDR=YES;FMT=Delimited';"; strSql = "select * from " + name; } else { return null; } DataSet ds = null; OleDbConnection conn = null; try { conn = new OleDbConnection(connstring); conn.Open(); OleDbDataAdapter myCommand = null; myCommand = new OleDbDataAdapter(strSql, connstring); ds = new DataSet(); myCommand.Fill(ds, "table1"); } catch (Exception e) { throw e; } finally { conn.Close(); } return ds; }