读取打开的Excel文件时出现OleDBException

我有一个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;
}

错误消息是

解决方法:

假设您不需要写入文件,请尝试调整连接字符串以包括只读模式(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;

上一篇:android-如果ListView /适配器为空,如何添加默认背景


下一篇:我在项目中使用带有PHP的工作单位设计模式