使用默认程序打开 Excel 文件
我的程序成功创建并填充了 Excel(.xls) 文件。创建后,我希望在系统的默认程序(在我的例子中是 Excel)中打开新文件。我怎样才能实现这个目标?
对于我想在记事本中打开 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();
}
当我尝试将此代码用于 Excel 文件时,它给出以下错误:
java.io.IOException: Failed to edit file:C:/foo.xls
建议?
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?
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();
}
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
Suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试使用 Desktop.open() 而不是 Desktop.edit() :
如果 Desktop.open() 不可用,则可以使用 Windows 文件关联:
Try to use Desktop.open() instead of Desktop.edit() :
If Desktop.open() is not available then the Windows file association can be used :
您可能错误地执行了 Runtime.exec。给 这个 看看是否是这样案件。
如果您只想使用 Java 打开 Excel 文件,我建议使用 Andy Khan 的 JExcel API。也许将其与 Swing JTable 一起使用就足够了。
You probably did the Runtime.exec incorrectly. Give this a look to see if that's the case.
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.
最简单有效的方法。
The most simple and efficient way.