Opening an Excel file using the default program
Asked Answered
M

3

12

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?

Mighty answered 22/1, 2010 at 1:23 Comment(1)
You may find similar answer here: <https://mcmap.net/q/210943/-how-to-open-a-file-with-the-default-associated-program>Automation
A
31

Try to use Desktop.open() instead of Desktop.edit() :

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

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);
Abreast answered 22/1, 2010 at 1:54 Comment(1)
@suman, maybe xdg-open to open the default application for a given file type, see manpages.ubuntu.com/manpages/trusty/en/man1/xdg-open.1.htmlAbreast
P
0

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.

Pointed answered 22/1, 2010 at 1:34 Comment(1)
Yes. Jexcel API prints colors more realistic than JRXlsExporter libraryMarriageable
C
0

The most simple and efficient way.

Desktop.getDesktop().open(new File("inputFilePath"));
Cody answered 23/6, 2017 at 10:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.