2013-12-13 137 views
3

我有一個excel文件和一個連接到它的oledb。在Windows打開文件時讀取數據時,會拋出以下錯誤(在Adapter.Fill方法中)。讀取打開的Excel文件時OleDBException

但是,當文件沒有手動打開時,代碼運行良好。

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

+4

'但是,當文件未被手動打開時,代碼運行正常。[可能使用OleDB c#讀取Excel文件其他進程](http://stackoverflow.com/questions/18798948/read-excel-file-with-oledb-c-when-it-is-used-by-other-process) –

+0

你設法解決這個問題嗎? – Nenotlep

+0

是的,Sid的解決方案爲我工作。 –

回答

3

假設你不需要寫入文件,請嘗試調整連接字符串包括只讀模式(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;