2010-01-22 50 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")); 
相關問題