Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening an Excel file using the default program

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?

like image 806
clang1234 Avatar asked Jan 22 '10 01:01

clang1234


People also ask

What is the default name of an Excel program?

Explanation: 1. Old name is spreadsheet. Explanation: The new default name of workbook in excel is Book1, Book2, Book3 etc...

Can't set Excel as default program?

There should be the option to set the default app/program in Apps and Features. Right click Start and select Apps and Features the Default apps and find xlsx in the list. Set it to Excel.

When Microsoft Excel opens by default?

The Excel Starter startup screen appears, and a blank spreadsheet is displayed. In Excel Starter, a spreadsheet is called a worksheet, and worksheets are stored in a file called a workbook. Workbooks can have one or more worksheets in them.


1 Answers

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);
like image 146
RealHowTo Avatar answered Sep 28 '22 19:09

RealHowTo