从java,如何在一个实例中给出多个电子表格的情况下在关闭excel电子表格时收到通知 [英] From java, how to be notified when excel spreadsheet is closed given multi spreadsheets in one instance

查看:28
本文介绍了从java,如何在一个实例中给出多个电子表格的情况下在关闭excel电子表格时收到通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 java 程序,可以为他们的命令行启动 excel 电子表格,并等待它关闭以执行如下下一步操作.(顺便说一句,我的 excel 运行宏,所以当我的宏完成执行以表明它已完成时,我会自动关闭电子表格)

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);

但是,我希望我的 Java 程序启动 2 个 excel 电子表格,并且每次关闭一张工作表时,我都想采取行动.excel 2010 使用一个 Excel 实例启动两个电子表格的问题.因此,我的 Java 程序仅检测 Excel 实例何时关闭,这意味着两个电子表格都必须关闭.

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.

我该如何解决?无论是Java代码、Excel代码,还是其他一些创新方法?请帮忙谢谢

How can I solve it ? Whether it is Java code, Excel code, some other innovative method? Please help Thank you

PS:我使用 apache poi 在开始前写入 excel 并在关闭后读取它

PS: I am using apache poi to write to excel before starting and read from it after closing

推荐答案

您可以定期打开文件进行写入(只需在附加模式下在其上打开一个普通的 FileOutputStream - 如果这引发了 IOException 那么该文件仍处于打开状态)

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;
    }
}

正如该方法的名称所暗示的那样,这不是跨平台的,它仅适用于 Windows,因为 Windows 不允许进程同时打开一个文件进行写入.

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.

既然您说的是 Excel,那么您很可能指的是 Windows,但有 Office for Mac,这个技巧在 Mac OS 上不起作用.

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.

这篇关于从java,如何在一个实例中给出多个电子表格的情况下在关闭excel电子表格时收到通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆