c# - 读取打开的 excel 文件时出现 OleDBException

标签 c# excel file adapter

我有一个 excel 文件和一个 oledb 连接。在 Windows 中打开文件时读取数据时,会抛出以下错误(在 Adapter.Fill 方法处)。

但是,当文件未手动打开时,代码运行正常。

private System.Data.DataSet GetExcelData()
{
    // Create new DataSet to hold information from the worksheet.
    System.Data.DataSet objDataset1 = new System.Data.DataSet();
    DataTable dt = new DataTable();
    try
    {
        string path = ConfigurationManager.AppSettings["ExcelFilePath"];
        //string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";

        string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";

        OleDbConnection objConn = new OleDbConnection(connectionString);
        objConn.Open();

        //String strConString = "SELECT * FROM [Data Version5.2$A2:ZZ] where [Status] = 'aa'";//Status
        String strConString = "SELECT * FROM [Data Version5.2$A2:ZZ] where [Status] IS NULL OR [Status]='SubReport'";//Status SubReport

        OleDbCommand objCmdSelect = new OleDbCommand(strConString, objConn);
        OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();

        // Pass the Select command to the adapter.  
        objAdapter1.SelectCommand = objCmdSelect;

        // Fill the DataSet with the information from the work sheet.
        objAdapter1.Fill(objDataset1, "ExcelData");

        objConn.Close();
    }
    catch (Exception ex)
    {
        throw ex;
    }

    return objDataset1;
}

错误信息是

enter image description here

最佳答案

假设您不需要写入文件,请尝试调整您的连接字符串以包含只读模式 (Mode=Read)。我的所有文件中都有它(我不需要写入文件)而且我从已经打开的工作簿中读取从来没有遇到过问题:

string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
    path + ";Mode=Read;Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";

我也不倾向于将 Excel 文件读取为 XML,因此我的连接字符串的扩展属性是 Excel 12.0;HDR=YES;IMEX=1;

关于c# - 读取打开的 excel 文件时出现 OleDBException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20568485/

相关文章:

python - 禁用特定文件的缓存/缓冲区 (Linux)

c# - 使用 ToArgb() 后跟 FromArgb() 不会产生原始颜色

c# - RCW 终结器访问冲突

c# - 在设计时设置 ComboBox 的 Text 和 Value 属性

java - 使用 Apache POI 从 Java 应用程序删除行时不更新 Excel 公式

sql - 在 OLEDB 源变量窗口中读取 for-each-loop 容器变量

r - 在R中并行下载多个文件

java - 同构词

c# - 测试工厂模式

excel - 打印电子表格的所有条件格式规则