Microsoft Jet 提供程序用於連接到 Excel 工作簿。在以下連接字符串中,Extended Properties 關鍵字設置 Excel 特定的屬性。“HDR=Yes;”指示第一行中包含列名,而不是數據,“IMEX=1;”通知驅動程序始終將“互混”數據列作為文本讀取。Excel 8.0 針對Excel2000及以上版本,Excel5.0 針對Excel97。
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:/MyExcel.xls;Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1""
注意,Extended Properties 所需的雙引號必須還要加雙引號。
Provider=Microsoft.Jet.OLEDB.4.0只支持Office97-2003,不支持2007。如果需要支持2007,使用 Provider='Microsoft.Ace.OLEDB.12.0
使用ADO.NET打開、讀取並關閉代碼示例如下:
using System.Data.OleDb; using System.Data; String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=c:/test.xls;" + "Extended Properties=Excel 8.0;"; OleDbConnection objConn = new OleDbConnection(sConnectionString); objConn.Open(); OleDbCommand objCmdSelect =new OleDbCommand("SELECT * FROM [sheet1]", objConn); OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(); objAdapter1.SelectCommand = objCmdSelect; DataSet objDataset1 = new DataSet(); //將Excel中數據填充到數據集 objAdapter1.Fill(objDataset1, "XLData"); objConn.Close();
string ConnnectionString = string.Format(@"Provider='Microsoft.Ace.OLEDB.12.0';Data Source={0};" + "Extended Properties=Excel 8.0;", ExcelPath); OleDbConnection Excelconn = new OleDbConnection(ConnnectionString); try { Excelconn.Open(); OleDbCommand Excelcomm = new OleDbCommand(); //這段代碼甚至可以讓Connection重定向,根據實際需要選擇該寫,如果不需要重定向,From TableName就好了
string ExcelCommText = string.Format("select * FROM [Excel 8.0;HDR=yes;DATABASE={0}].[{1}$]", ExcelPath, TableName);
OleDbDataAdapter sda = new OleDbDataAdapter(ExcelCommText, Excelconn); DataSet ds = new DataSet(); sda.Fill(ds);
從上面可以看出,使用ADO.NET可將Excel當作普通數據庫,使用SQL語句來操作。
通過ADO.NET獲取Excel文件的各Sheet名稱,可使用元數據方式:
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=c:/test.xls;" + "Extended Properties=Excel 8.0;"; OleDbConnection cn = new OleDbConnection(sConnectionString); cn.Open(); DataTable tb = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); foreach (DataRow row in tb.Rows) { //遍歷彈出各Sheet的名稱 MessageBox.Show(row["TABLE_NAME"]); }
關於使用ADO.NET創建並寫入Excel文件與普通數據庫操作極為類似,參見以下代碼:
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=c:/test.xls;" + "Extended Properties=Excel 8.0;"; OleDbConnection cn = new OleDbConnection(sConnectionString); string sqlCreate = "CREATE TABLE TestSheet ([ID] INTEGER,[Username] VarChar,[UserPwd] VarChar)"; OleDbCommand cmd = new OleDbCommand(sqlCreate, cn); //創建Excel文件:C:/test.xls cn.Open(); //創建TestSheet工作表 cmd.ExecuteNonQuery(); //添加數據 cmd.CommandText = "INSERT INTO TestSheet VALUES(1,'elmer','password')"; cmd.ExecuteNonQuery(); //關閉連接 cn.Close();
另一版本Update參考代碼
string ConnnectionString = string.Format(@"Provider='Microsoft.Ace.OLEDB.12.0';Data Source={0};" + "Extended Properties=Excel 8.0;", ExcelPath); OleDbConnection Excelconn = new OleDbConnection(ConnnectionString); Excelconn.Open(); OleDbCommand Excelcomm = new OleDbCommand(); //~ where XXX=’’ 在SQL中應改成 XXX is null ExcelCommText=string.Format("update [{0}$] set error = '{1}' where XXX is null",TableName, row["error"].ToString()); Excelcomm.CommandText = ExcelCommText; Excelcomm.Connection = Excelconn;//OleDbCommand 也需Connection屬性,可以直接用OleDbConnection賦給 Excelcomm.ExecuteNonQuery();
直接讀取Excel,寫入Acces的方法
public bool InsertAccess(string AccessPath, string AccessName, string TableName, string ExcelPath,out string vErr) { bool bRet = false; vErr = string.Empty; try { vErr = string.Empty; string ConnnectionString = string.Format(@"Provider='Microsoft.Ace.OLEDB.12.0';Data Source={0}\\{1}.accdb", AccessPath, AccessName); OleDbConnection Accessconn = new OleDbConnection(ConnnectionString); try { Accessconn.Open(); OleDbCommand Accesscomm = new OleDbCommand(); string AccessCommText = string.Format(" SELECT * INTO [{0}] FROM [Excel 8.0;DATABASE={1}].[{2}$]", TableName.Replace("'", ""), ExcelPath, TableName.Replace("'", "")); //string AccessCommText = string.Format(" insert INTO [{0}] select * FROM [Excel 8.0;HDR=yes;DATABASE={1}].[{2}$]", TableName, ExcelPath, TableName); Accesscomm.CommandText = AccessCommText; Accesscomm.Connection = Accessconn; Accesscomm.ExecuteNonQuery(); bRet = true; } catch (Exception vTemp) { vErr += vTemp.Message + "\r\n"; } finally { Accessconn.Close(); Accessconn.Dispose(); } } catch (Exception ex) { vErr += ex.Message + "\r\n"; } return bRet; }
關於SQL語句中用到的數據類型,請查看System.Data.OleDb.OleDbType 枚舉。
至此,使用ADO.NET打開、創建、讀取、寫入、保存並退出已全部實現,總結起來,與數據庫操作基本無異,很簡單。這種方式的好處就是通用性強,將Excel中內容看作數據表,讀取操作簡單可靠,適合內容規范的Excel表格的數據讀取。缺點是當Excel結構復雜,如含合並單元等時,無法正確讀取,甚至出現不可預知的異常。