Java 使用默认程序打开 Excel 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2114318/
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
Opening an Excel file using the default program
提问by clang1234
My program successfully creates and fills a Excel(.xls) file. Once created, I would like the new file to open in the system's default program (Excel in my case). How can I achieve this?
我的程序成功创建并填充了 Excel(.xls) 文件。创建后,我希望新文件在系统的默认程序(在我的情况下为 Excel)中打开。我怎样才能做到这一点?
For an older program where I wanted to open a txt file in Notepad, I used the following:
对于我想在记事本中打开 txt 文件的旧程序,我使用了以下内容:
if (!Desktop.isDesktopSupported()) {
System.err.println("Desktop not supported");
// use alternative (Runtime.exec)
return;
}
Desktop desktop = Desktop.getDesktop();
if (!desktop.isSupported(Desktop.Action.EDIT)) {
System.err.println("EDIT not supported");
// use alternative (Runtime.exec)
return;
}
try {
desktop.edit(new File(this.outputFilePath));
} catch (IOException ex) {
ex.printStackTrace();
}
When I try to use this code for an Excel file it gives me the following error:
当我尝试将此代码用于 Excel 文件时,它给了我以下错误:
java.io.IOException: Failed to edit file:C:/foo.xls
Suggestions?
建议?
采纳答案by RealHowTo
Try to use Desktop.open() instead of Desktop.edit() :
尝试使用 Desktop.open() 而不是 Desktop.edit() :
Desktop dt = Desktop.getDesktop();
dt.open(new File(this.outputFilePath));
If Desktop.open() is not available then the Windows file association can be used :
如果 Desktop.open() 不可用,则可以使用 Windows 文件关联:
Process p =
Runtime.getRuntime()
.exec("rundll32 url.dll,FileProtocolHandler " + this.outputFilePath);
回答by duffymo
You probably did the Runtime.exec incorrectly. Give thisa look to see if that's the case.
您可能错误地执行了 Runtime.exec。给这个看看,看看是否是这种情况。
If you just want to open an Excel file with Java, I'd recommend using Andy Khan's JExcel API. Perhaps using that with a Swing JTable will be just the ticket.
如果您只想用 Java 打开 Excel 文件,我建议您使用 Andy Khan 的 JExcel API。也许将它与 Swing JTable 一起使用将是唯一的选择。
回答by Junaid Khan
The most simple and efficient way.
最简单有效的方法。
Desktop.getDesktop().open(new File("inputFilePath"));