Java - Run Excel using runtime.getRuntime().exec

大兔子大兔子 提交于 2020-01-01 15:03:35

问题


try {
    Runtime.getRuntime().exec("excel C:\\file.xls");
} catch (IOException ex) {
    System.out.println(ex);
}

Doesn't work. I have to put the full path of excel.exe in order to work. How can I make it generic (For any Excel Folders/Versions)? When I run the same line from OS with Windows Run (Start --> Run) it works. Is there a code in Java to simulate Windows' Run command?


回答1:


Why don't you try with the Desktop class (api doc here) introduced in JDK6 that has the method

public void open(File file) throws IOException

which is documented as what you want to do:

Launches the associated application to open the file. If the specified file is a directory, the file manager of the current platform is launched to open it.

Of course this assumes that .xls extension is mapped by OS to Excel. Then you can go with

Desktop.getDesktop().open(new File("c:\\file.xls"));



回答2:


I use Runtime rt = Runtime.getRuntime().exec("cmd.exe /C start " + *filename* it works for me on Windows platforms




回答3:


Call the Windows "start.exe" command instead of Excel directly. Start.exe appears to search paths, etc. However, it still may not find it if it's not in the path.




回答4:


You might try using "cmd" instead of "excel", and then pass in an array of params.

For easier debugging, you might also try using ProcessBuilder instead. In my experience it's much nicer to work with: http://download.oracle.com/javase/6/docs/api/java/lang/ProcessBuilder.html



来源:https://stackoverflow.com/questions/3978369/java-run-excel-using-runtime-getruntime-exec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!