Checking whether excel file is opened?

27 views (last 30 days)
Pete sherer
Pete sherer on 14 Sep 2023
Edited: dpb on 14 Sep 2023
I have run into an issue where excel file was somehow opened (due to slow ethernet speed)
Unable to write to file 'asAt20230831_20230914_1748.xlsx'. You may not have write permissions
or the file may be open by another application.
Is there a way to check whether the file is opened, if so don't try to writetable yet, waiting till file is closed, then execute writetable.

Answers (2)

Star Strider
Star Strider on 14 Sep 2023
The fopen function can return information about MATLAB instances of the open files, however I am not certain that it can go beyond that.
See the documentation section on Get Information About Open Files for details on what it can do. (Anything else might be more of an operating-system level exploration, and that depends on the operating system.)

dpb
dpb on 14 Sep 2023
Edited: dpb on 14 Sep 2023
Excel creates a hidden file of the same base name prefixed with "~$" when it opens a file -- this is the backup copy. This file is transparent to the user and is deleted when the file is closed normally. I've been pretty successful in utilizing this in a GUI app to ensure the user has closed the file first before trying to write to it, but that's on a local machine. If you have latency issues with a remote connection, that'll make things tricky for that file as well.
NOTA BENE: If for some reason (like messing with COM and making a syntax error that crashes MATLAB with the file open) the Excel process is killed externally, the original file may be closed but the companion file in that case won't have been deleted automagically. You shouldn't run across this issue if you're only using the high level MATLAB functions and not munging directly through COM (and even there only during debugging, but something to be aware of if using this method).
I've found no way otherwise to do so other than another COM session and try to attach to/open the same file and trap error or use try...catch block in the high-level code; the task list data from the OS process doesn't have the filename(s) that the app has open, only that the process is running, etc., ...

Products


Release

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!