2013-08-01 45 views
1

我在應用程序中打開多個excel文件。有些會在應用程序啓動時自動打開,而有些則在運行時打開。如何檢查excel工作簿已在C#win表格中打開

現在我想從按鈕點擊的Excel文件中獲取數據。但在打開它之前,我想檢查一下excel文件是否已經打開。

  1. 如果開放,我想從它直接讀取。
  2. 如果是未打開,我想打開它並從中讀取。

但在這兩個,我不想reading.`

我使用這個方法打開Excel文件後,關閉文件的情況下。

objExcel = new Excel.ApplicationClass(); 
objWorkbook = objExcel.Workbooks.Open(...);` 

請幫忙我是C#的新手。

+0

可能的重複:http://stackoverflow.com/questions/6686886/how-to-access-an-already-opened-excel-file-in-c – Recipe

+0

VBA示例:http://stackoverflow.com/questions/9373082/detect-whether-excel-workbook-is-already-open-using-vba –

+0

另一個VBA檢查:http://stackoverflow.com/questions/3156676/checking-if-an-excel-workbook-is-open – martin

回答

2

如果我理解正確,你實際上是想找到一些文件是否已經被這個winform應用程序打開了,對吧?

如果是的話,我認爲它應該是相當簡單 - 只要緩存打開工作簿一些字典左右:

static Dictionary<string, Workbook> _openedWorkBooks = new Dictionary<string, Workbook>();  
    public static Workbook GetWorkbook(string filePath) {  
     Workbook wkb = null;  
     if (!(_openedWorkBooks.TryGetValue(filePath, out wkb)))  
     { 
      // Open the file and store it into the dictionary  
     } 

     return wkb; 
    } 

    // remember to remove it when it's closed 
    public static CloseWorkbook() 
    { // need to remove the corresponding key from the dictionary 
    } 

還,您可以使用Excel應用程序的單一實例一樣,那麼所有打開的工作簿可能會從App.Workbooks中黯然失色,但是,它有時會拋出一些異常(不知道爲什麼,但我以前遇到過)。

  var app = new Microsoft.Office.Interop.Excel.Application(); 
      var bk1 = app.Workbooks.Open("c:\temp\myfile.xls"); 
      var allOpenBks = app.Workbooks; 

實際上它仍然值得調用IsFileLock方法來檢查該文件已被其他應用程序打開的,否則你可能會遇到一些錯誤。

-1

您可以checkk,如果你有讀寫訪問:

 /// <summary> 
    /// Check wether a file is locked 
    /// </summary> 
    /// <param name="file"></param> 
    /// <returns></returns> 
    public static bool IsFileLocked(FileInfo file) 
    { 
     FileStream stream = null; 

     try 
     { 
      stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); 
     } 
     catch (IOException) 
     { 
      //the file is unavailable because it is: 
      //still being written to 
      //or being processed by another thread 
      //or does not exist (has already been processed) 
      return true; 
     } 
     finally 
     { 
      if (stream != null) 
       stream.Close(); 
     } 

     //file is not locked 
     return false; 
    } 

的代碼是從另外一個人在計算器上。

做.xlsx?如果是這樣,您可以用於讀取和寫入Excel文件OpenXML。

+2

你應該相信其他人 – Sayse

+0

你是什麼意思?如果他有讀寫訪問權限,則不會打開excel文件。因爲excel總是鎖定打開的文件。 – BendEg

+0

正如其他人所說,如果打開文件以防止非法修改,Excel將鎖定該文件 – aceminer

相關問題