Is there a way to see if an Excel Workbook, say DataSheet.xls, is open (in use) or not? I would like to close that Workbook if it is opened.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
Try this:
This will tryand open the file exclusively. If the file is already open it will throw an exception, where you can then (try to) close it and carry on.
For anyone interested in a one liner that avoids using a try-catch...
Or with fully qualified names...
Of course, you may want to split this up a little. The main point is to use LINQ instead of try-catch to check for the workbook's existence.
Note 1:
Marshal.GetActiveObject("Excel.Application")
will throw an error if no instance of Excel is open. So unless otherwise guarantied or handled this should always be within a try-catch.Note 2:
Marshal.GetActiveObject("Excel.Application")
will only return one instance of Excel. If you need to search any possible instance of Excel then the code below may be a better alternative.Better Alternative
If you don't mind adding a helper class the code below may be a better alternative. Aside from being able to search any opened instance of Excel, it also allows you to check the full path and return the actual workbook object if found. It also avoids throwing an error if no instance of Excel is opened.
usage would be like this...
or
I adapted the
GetRunningObjects()
method in the code above from here.If you have worksheet and workbook objects them you can do parent check
if (sheet.Parent == workbook)
The right way is to examine the Application.Workbooks object. In VBA you would write:
In other words, Workbooks is an array (or in VBA terms, Collection) of all open workbooks.
In C# the following code works:
You will probably want to pass the reference to Excel.Application yourself.
This is not especially nice - we'll try and open the file and examine the exception if it fails. I'm not sure you have any other choices in C#.
However, it is important to only handle the correct exception: Basically we try open the file with no sharing allowed. If it fails, AND we get the correct type of exception AND we get the correct message in the exception, then we know it is open.
Obviosuly this sort of approach is brittle with respect to the exception message being changed in a future release of .Net. You may wish to complement such functionality with a test that purposely locks a file and then calls this to check it correctly detects the message.
martin's answer does not work if Excel Application is not currently running. You may want to modifiy the code as following :
Thank you for your attention. Regards