如果我理解正確,你實際上是想找到一些文件是否已經被這個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方法來檢查該文件已被其他應用程序打開的,否則你可能會遇到一些錯誤。
來源
2013-08-01 08:35:00
Rex
可能的重複:http://stackoverflow.com/questions/6686886/how-to-access-an-already-opened-excel-file-in-c – Recipe
VBA示例:http://stackoverflow.com/questions/9373082/detect-whether-excel-workbook-is-already-open-using-vba –
另一個VBA檢查:http://stackoverflow.com/questions/3156676/checking-if-an-excel-workbook-is-open – martin