问题
I have java program that starts excel spreadsheet for them command line and wait for it to be closed to take next action as below. (btw my excel runs macro so I close the spreadsheet automatically when my macro finish executing to indicate it is done)
p = Runtime.getRuntime().exec("cmd /c start /wait C:\\"+excelSheet);
p.waitFor();
System.out.print("finished "+count + " "+ excelSheet);
However I want my java program to starts 2 excel spreadsheets and each time one sheet closes, I want to take action. The problem that excel 2010 starts both spreadsheets using one instance of Excel. Therefore my java program only detects when the instance of the Excel is closed which means both spreadsheets has to close.
How can I solve it ? Whether it is Java code, Excel code, some other innovative method? Please help Thank you
PS: I am using apache poi to write to excel before starting and read from it after closing
回答1:
You can periodically open the file for writing (just open a normal FileOutputStream
on it in append mode - if this raises an IOException then the file is still open)
public boolean isStillOpenOnWindows(File file) {
try {
FileOutputStream out = new FileOutputStream(file, true);
out.close();
// Not open anymore
return false;
} catch (IOException e) {
// Still open
return true;
}
}
As the name of the method implies, this is not cross-platform, it only works on Windows because Windows doesn't allow to processes to have a file open for writing at the same time.
Since you're talking about Excel, it's likely that you mean Windows, but there is Office for Mac and this trick wouldn't work on Mac OS.
来源:https://stackoverflow.com/questions/22278082/from-java-how-to-be-notified-when-excel-spreadsheet-is-closed-given-multi-sprea