从Java应用程序打开Excel

Man*_*shi 5 java excel runtime

如果我想从Java应用程序中打开记事本,那么它将打开记事本,但是如果我尝试打开Excel,则它给了我例外。

try
    {
        Runtime.getRuntime().exec("excel");
    }
    catch (IOException e) 
    {
      e.printStackTrace();
    }
Run Code Online (Sandbox Code Playgroud)

以下是例外:

java.io.IOException: Cannot run program "excel": CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at OpenNotepad.main(OpenNotepad.java:18)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(Unknown Source)
    at java.lang.ProcessImpl.start(Unknown Source)
    ... 5 more
Run Code Online (Sandbox Code Playgroud)

当我开始->运行-> Excel时,它将打开excel。

小智 5

Runtime.getRuntime().exec("some command");与“某些命令”在 cmd 中的作用相同。所以打开Excel的解决方案你应该试试这个。

try {
    Runtime.getRuntime().exec("cmd /c start excel.exe");
} catch (IOException e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)


小智 0

在 exec 方法中给出安装 excel 的完全限定路径,然后尝试 RunTime 很好,但最好使用 ProcessBuilder