2010-01-22 102 views
10

我的程序成功创建并填充了Excel(.xls)文件。一旦创建,我想在系统的默认程序中打开新文件(在我的情况下为Excel)。我怎样才能做到这一点?使用默认程序打开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 

建议?

+0

您可能会在这里找到类似的答案: jayaneetha 2016-04-11 08:51:18

回答

29

尝试使用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); 
+0

谢谢,这很好用 – clang1234 2010-01-22 20:07:22

+0

如果我使用unix机器而不是windows – Suman 2016-09-15 12:48:04

+0

@suman,也许'xdg-open'打开给定文件类型的默认应用程序,请参见http: //manpages.ubuntu.com/manpages/trusty/en/man1/xdg-open.1.html – RealHowTo 2016-09-15 21:13:45

0

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

如果您只是想用Java打开Excel文件,我会推荐使用Andy Khan的JExcel API。也许在Swing JTable中使用它只是门票。

+0

是的。 Jexcel API打印的颜色比JRXlsExporter库更真实 – StarCrafter 2016-02-10 09:24:14

0

最简单有效的方法。

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