C#通過OleDb訪問Excel 錯誤信息:未在本地計算機上注冊“microsoft.ACE.oledb.12.0”提供程序。網上查詢得知需要下載安裝Microsoft Access 2010 數據庫引擎可再發行程序包。下載地址為:https://www.microsoft.com/zh-CN/download/details.aspx?id=13255。
支持的操作系統
Windows 7, Windows 8, Windows Server 2003, Windows Server 2003 Service Pack 1, Windows Server 2003 Service Pack 2, Windows Server 2008 R2, Windows Server 2008 Service Pack 2, Windows Vista Service Pack 1, Windows XP Service Pack 2
-
只有 32 位 Access 數據庫引擎可在 Windows XP Service Pack 3 上使用
使用場景:
- 如果使用 OLEDB 的應用程序,將 ConnectionString 屬性的 Provider 參數設置為“Microsoft.ACE.OLEDB.12.0”。
如果連接到 Microsoft Office Excel 數據,根據 Excel 文件類型添加相應的 OLEDB 連接字符串擴展屬性:
文件類型(擴展名) 擴展屬性
---------------------------------------------------------------------------------------------
Excel 97-2003 工作簿 (.xls) “Excel 8.0”
Excel 2007-2010 工作簿 (.xlsx) “Excel 12.0 Xml”
啟用宏的 Excel 2007-2010 工作簿 (.xlsm) “Excel 12.0 宏”
Excel 2007-2010 非 XML 二進制工作簿 (.xlsb) “Excel 12.0” - 如果您是使用 ODBC 連接到 Microsoft Office Access 數據的應用程序開發人員,請將連接字符串設置為“Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=path to mdb/accdb file”
- 如果您是使用 ODBC 連接到 Microsoft Office Excel 數據的應用程序開發人員,請將連接字符串設置為“Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=path to xls/xlsx/xlsm/xlsb file”
一個測例子:
1 public static DataTable GetData(string fileName) 2 { 3 if (!File.Exists(fileName)) return null; 4 //string connStr = string.Format(@"Provider=MMicrosoft.ACE.OLEDB.12.0;data source='{0}';Extended Properties='Excel 8.0;HDR=YES;IMEX=1';", fileName); 5 string connStr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;data source='{0}';Extended Properties='Excel 12.0;HDR=YES;IMEX=1';", fileName); 6 using (OleDbConnection conn = new OleDbConnection(connStr)) 7 { 8 9 try 10 { 11 conn.Open(); 12 DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); 13 var tableName = dt.Rows[0][2].ToString().Trim(); 14 string cmdTxt = string.Format("select * from [{0}]", tableName); 15 16 // Trace.Write("查詢表:" + cmdTxt); 17 OleDbDataAdapter da = new OleDbDataAdapter(cmdTxt, conn); 18 DataSet ds = new DataSet(); 19 da.Fill(ds); 20 return ds.Tables[0]; 21 } 22 catch (Exception e) 23 { 24 25 // Trace.WriteLine("GetData錯誤: " + e.Message); 26 return null; 27 } 28 finally 29 { 30 conn.Close(); 31 } 32 } 33 }