Java - 使用 runtime.getRuntime().exec 运行 Excel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3978369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 04:14:47  来源:igfitidea点击:

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

javaexcelruntimeexecruntime.exec

提问by Stefanos Kargas

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?

不起作用。我必须输入 excel.exe 的完整路径才能工作。我怎样才能使它通用(对于任何 Excel 文件夹/版本)?当我使用 Windows 运行(开始 --> 运行)从操作系统运行同一行时,它可以工作。Java 中是否有代码来模拟 Windows 的运行命令?

回答by Hyman

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

为什么不尝试使用JDK6 中引入的具有该方法的Desktop类(此处的api 文档)

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 .xlsextension is mapped by OS to Excel. Then you can go with

当然,这假设.xls扩展名由操作系统映射到 Excel。然后你可以去

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

回答by Fabrice Khedadi

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

Runtime rt = Runtime.getRuntime().exec("cmd.exe /C start " + *filename*我在 Windows 平台上使用它对我有用

回答by Brian Knoblauch

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.

直接调用 Windows“start.exe”命令而不是 Excel。Start.exe 似乎在搜索路径等。但是,如果它不在路径中,它仍然可能找不到它。

回答by marc esher

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

您可以尝试使用“cmd”而不是“excel”,然后传入参数数组。

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

为了更容易调试,您也可以尝试改用 ProcessBuilder。根据我的经验,使用它会更好:http: //download.oracle.com/javase/6/docs/api/java/lang/ProcessBuilder.html