简体   繁体   中英

Open Excel from Java Application

If I am tring to open notepad from Java Application then it will open Notepad.But If I will try to open Excel then it is giving me exception.

try
    {
        Runtime.getRuntime().exec("excel");
    }
    catch (IOException e) 
    {
      e.printStackTrace();
    }

Following is Exception :

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

When I do start->Run->Excel then it will open excel.

Runtime.getRuntime().exec("some command"); does the same as "some command" will do in cmd. So the solution for opening Excel you should try this.

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

If you are trying to use Java to open an Excel file, rather than just opening Excel, I suggest you use the Desktop API class: http://docs.oracle.com/javase/6/docs/api/java/awt/Desktop.html

This class will use the default OS file handling mechanism, so it will use say MS Excel in Windows, and Open Office in Linux.

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

Runtime.getRuntime().exec() is the same thing as doing something from the command line.

In windows OS there is an environment variable set to C:\\Windows\\System32 all the exe of commands are in this path.

when I do following in cmd I get this.

C:\Users\bhaviksh>echo %PATH%
D:\oracle\product\10.2.0\client_1\bin;C:\Windows\system32;C:\Windows;C:\Windows\
System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\MySQL
\MySQL Server 5.0\bin;C:\Program Files\cvsnt;C:\Program Files\TortoiseSVN\bin;C:
\maven\bin

Solution : use fully qualified name of exe file

Add microsoft office excel executable path for eg: If Directory C:\\Program Files (x86)\\Microsoft Office\\Office14 has EXCEL.EXE then add C:\\Program Files (x86)\\Microsoft Office\\Office14 to your classpath. How to add to classpath Click here . Once you are done, restart your IDE, your program should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM