填充 DataTable 时出现 AccessViolationException

AccessViolationException when filling DataTable

我遇到了一个工具的奇怪问题,它应该能够从 Excel 文件读取数据并将其写入 SQL-数据库。

            string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" +
                        "Data Source=" + filename + ";" +
                        "Extended Properties=\"Excel 12.0 Xml;HDR=YES\"";
        DataTable dt;
        OleDbDataAdapter dataAdapter;
        dataAdapter = new OleDbDataAdapter("SELECT * FROM [" + sheet + "$]", strConn);
        dt = new DataTable();
        try
        {
            dataAdapter.Fill(dt);   //Programm reagiert nicht mehr
        }
        catch(Exception ex)
        {
            Logger("Problem filling Adapter: " + ex.ToString());
            return null;
        }

以下异常发生在dataAdapter.Fill(dt)

Problem filling Adapter: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at System.Data.OleDb.DataSourceWrapper.InitializeAndCreateSession(OleDbConnectionString constr, SessionWrapper& sessionWrapper) at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection) at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject) at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup) at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) at System.Data.OleDb.OleDbConnection.Open() at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior) at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable) at ExcelExportWindowsForms.Program.ReadExcel(String filename, String sheet)

有趣的是,这在我的机器上运行良好(Excel 2013),但在 Excel 2003 的服务器上却不能。这可能是原因吗?

(来自评论)

在您的评论中,您提到您安装了最新的 AccessDatabaseEngine。我也遇到过这个问题(当时我发现很多人有同样的问题,但没有这些链接了)。我不得不使用2010版本。如果所有其他方法都失败了,可以尝试一下(您可能必须先卸载其他版本)。 原因尚不清楚(无论如何对我来说),但它可能与 x86 v x64 安装有关。

使用 Microsoft.ACE.OLEDB.16.0(同时尝试 32 位和 64 位),System.AccessViolationException 在 Windows Server 2012(64 位)上多次读取 MS Access 文件仍然是一个问题). 将参数 OLE DB Services = -1 添加到连接字符串似乎可以解决我的问题。 参数说明在 MSDN 并在 CodeProject

上提出了修复建议

对我来说,问题是它试图访问的文件被 Excel 以某种方式锁定,因为我既无法删除也无法移动该文件。我首先尝试打开任务管理器以停止 Excel,但在那里找不到 Excel,所以我只是重新启动了计算机,这很有效。