使用默认程序打开Excel文件

我的程序成功创build并填充Excel(.xls)文件。 一旦创build,我想在系统的默认程序中打开新文件(在我的情况下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 

build议?

尝试使用Desktop.open()而不是Desktop.edit():

 Desktop dt = Desktop.getDesktop(); dt.open(new File(this.outputFilePath)); 

如果Desktop.open()不可用,则可以使用Windows文件关联:

 Process p = Runtime.getRuntime() .exec("rundll32 url.dll,FileProtocolHandler " + this.outputFilePath); 

您可能错误地执行了Runtime.exec。 看看这是否是这种情况。

如果你只是想用Java打开Excel文件,我build议使用Andy Khan的JExcel API。 也许在Swing JTable中使用它就是门票。

最简单有效的方法。

 Desktop.getDesktop().open(new File("inputFilePath"));