在使用Excel的连接字符串时,如何解决“ System.InvalidOperationException”类型的异常?

时间:2019-09-04 05:47:28

标签: c# excel ado.net oledbconnection

我正在尝试将excel文件连接到我的C#代码。但是,代码将引发异常:“'ServerVersion'引发了类型'System.InvalidOperationException'的异常”?我该如何解决?

    OleDbConnection con = new OleDbConnection();
    con.ConnectionString= "Provider=Microsoft.ACE.OLEDB.12.0;DataSource='D:/.Net devlop/ADO_QuickKart Application_14Nov16_1807/QuikkartDB.xlsx';Extended Properties='Excel 12.0 Xml;HDR=YES'";

2 个答案:

答案 0 :(得分:0)

您的路径包含',这导致了问题。

示例:

Data Source=c:\myFolder\myExcel2007file.xlsx;

答案 1 :(得分:0)

以\和'开头。

string filePath = "D:\\.Net devlop\\ADO_QuickKart Application_14Nov16_1807\\QuikkartDB.xlsx";

string connectionString = $"Provider=Microsoft.ACE.OLEDB.12.0; Data Source={filePath};Extended Properties=\"Excel 12.0;HDR=YES;\"";

或使用OleDb。OleDbConnectionStringBuilder

OleDb.OleDbConnectionStringBuilder Builder = new OleDb.OleDbConnectionStringBuilder();
Builder.DataSource = "test.xlsx";
Builder.Provider = "Microsoft.ACE.OLEDB.12.0";
Builder.Add("Extended Properties", "Excel 12.0;HDR=Yes;IMEX=1");
Console.WriteLine(Builder.ConnectionString);