[英]Unspecified Error thrown when opening connection to excel file using OLEDB
I am working on reading in excel files (both.xls and.xlsx) into my program which is being written into a data table.我正在将 excel 文件(.xls 和 .xlsx)读入我的程序中,该程序正在写入数据表中。 When running the code on one computer it works perfectly fine, when I attempt to run it on another computer I get the following exception:
在一台计算机上运行代码时,它工作得很好,当我尝试在另一台计算机上运行它时,我得到以下异常:
System.Data.OleDb.OleDbException (0x80004005): Unspecified error at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection)
System.Data.OleDb.OleDbException (0x80004005): System.Data.OleDb.OleDbConnectionInternal..ctor (OleDbConnectionString constr, OleDbConnection connection) 出现未指定错误
This exception is thrown when the program attempts to open the connection to the excel file to read the data in. I have installed 2010 Access Database Engine on the other computer but I still receive the same error when running the code.当程序尝试打开与 excel 文件的连接以读取数据时,将引发此异常。我在另一台计算机上安装了 2010 Access 数据库引擎,但在运行代码时仍然收到相同的错误。 I was trying to get around the use of the Excel Interop services as it took too long to read in some of the file I am working with.
我试图绕过 Excel 互操作服务的使用,因为读取我正在使用的某些文件需要很长时间。 I have done some searching around and have tried various different solutions such as different modifications to the connection string and changing with OLEDB driver I am using to open the connection to the file.
我已经进行了一些搜索并尝试了各种不同的解决方案,例如对连接字符串的不同修改以及使用我用来打开文件连接的 OLEDB 驱动程序进行更改。 This is the code I am using,
这是我正在使用的代码,
private static DataTable ReadExcelData(String path, String TableName)
{
string ConnectionString = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={path};Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'";
DataTable dt = new DataTable(TableName);
using (OleDbConnection conn = new OleDbConnection(ConnectionString))
{
conn.Open();
DataTable table = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
String sheetName = table.Rows[0]["TABLE_NAME"].ToString();
using (OleDbCommand comm = new OleDbCommand("SELECT * FROM [" + sheetName + "$]", conn))
using (OleDbDataAdapter da = new OleDbDataAdapter(comm))
da.Fill(dt);
conn.Close();
}
return dt;
}
Figured out the issue, I had to installed the 2016 version of the driver and not the 2010 version which allowed it to work properly.解决了这个问题,我必须安装 2016 版本的驱动程序,而不是 2010 版本才能使其正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.