使用默认程序打开Excel文件 [英] Opening an Excel file using the default program
本文介绍了使用默认程序打开Excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的程序成功创建并填充Excel(.xls)文件。一旦创建,我希望新文件在系统的默认程序(我的情况下为Excel)中打开。如何实现这一点?
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?
对于我想在记事本中打开txt文件的较旧的程序,我使用以下内容:
For an older program where I wanted to open a txt file in Notepad, I used the following:
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();
}
当我尝试将此代码用于Excel文件时,它给了我以下错误:
When I try to use this code for an Excel file it gives me the following error:
java.io.IOException: Failed to edit file:C:/foo.xls
建议?
推荐答案
尝试使用Desktop.open()而不是Desktop.edit():
Try to use Desktop.open() instead of Desktop.edit() :
Desktop dt = Desktop.getDesktop();
dt.open(new File(this.outputFilePath));
如果Desktop.open()不可用,则可以使用Windows文件关联:
If Desktop.open() is not available then the Windows file association can be used :
Process p =
Runtime.getRuntime()
.exec("rundll32 url.dll,FileProtocolHandler " + this.outputFilePath);
这篇关于使用默认程序打开Excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文