初始化string的格式不符合OLE DB规范
尝试使用第三方组件读取Excel文件时出现以下错误
初始化string的格式不符合OLE DB规范
现在,我知道“第三方组件”这个词会在这里发出警钟,但是听我说。
这是我正在使用的连接string
Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\users\rory\downloads\testdb_4.xls; Extended Properties='Excel 8.0;HDR=YES;';
我有这个确切的连接string工作没有问题,以下的C#代码
using (OleDbConnection conn = new OleDbConnection()) { DataTable dt = new DataTable(); conn.ConnectionString = connstring; using (OleDbCommand comm = new OleDbCommand()) { comm.CommandText = "select * from [TEST_DB$]"; // TEST_DB is the name of the sheet comm.Connection = conn; using (OleDbDataAdapter da = new OleDbDataAdapter()) { da.SelectCommand = comm; da.Fill(dt); // do stuff with dt } } }
这按预期工作,数据表中填充了Excel文件中的数据。 但是,当我尝试从组件访问它,我得到上面的错误。
我不是OLE DB的专家,但是我的印象是驱动程序在操作系统级别,如果他们为一个应用程序/连接string工作,他们应该为所有具有相同连接string的应用程序工作。 我错了吗? 如果是这样,有没有人知道这里发生了什么?
我已经联系了该组件的支持。
解决这个问题的办法就是用逃脱的双打replace单引号。
string conn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=C:\users\rory\downloads\testdb_4.xls;" + "Extended Properties='Excel 8.0;HDR=YES;'"; // single quotes
成为
string conn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=C:\users\rory\downloads\testdb_4.xls;" + "Extended Properties=\"Excel 8.0;HDR=YES;\""; // escaped double quotes
OleDbConnection
没有单引号的问题,但显然有一些应用程序和组件。