2012-10-04 53 views
3

我正在閱讀使用C#的excel文件,下面是正在按預期工作的代碼除了每次運行應用程序時,我都必須關閉excel文件,否則我得到了以下錯誤消息:Excel文件 - 它已經由另一個用戶專門打開,

The Microsoft Access database engine cannot open or write to the file ''. It is already opened exclusively by another user, or you need permission to view and write its data..

我的問題是:有沒有一種方法,我關閉Excel文件一次我正在閱讀完?

public static DataTable LoadExcelWorkbook(string workbookName) 
     { 
      OleDbConnection connection; 

      string connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", EXCELFILENAME); 
      string query = String.Format("select * from [{0}$]", workbookName); 

      using(OleDbConnection conn = new OleDbConnection(connectionString)) 
      { 
       connection = new OleDbConnection(connectionString); 
       connection.Open(); 

       OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString); 
       DataSet dataSet = new DataSet(); 
       dataAdapter.Fill(dataSet); 

       DataTable myTable = dataSet.Tables[0]; 

       dataAdapter.Dispose(); 
       connection.Close(); 
       dataSet.Dispose();    

       //CLOSE THE EXCEL FILE????????? 

       if (myTable != null) 
        return myTable; 

       return null; 
      } 
     } 
+0

嘗試在這篇文章中提出的解決方案 http://stackoverflow.com/questions/8710510/c-sharp-excel-doesnt-close-itself- when-using-oledbconnections-open-method – Tariqulazam

+0

你解決了嗎? – levi

回答

0

使用工作表Sheet1名稱,而不是工作簿名稱

相關問題