4

I'm making a project in which the user has to give in a document with data. The program reads the data and makes some diagrams. It al works perfectly but i want to open the ExcelFile when the user has saved it...So I know the directory of the Excelfile but i don't know how to open an excelfile in javaFX, can someone help me?

kind regards

6
  • 1
    Can you clarify? Are you wanting to read the contents of an Excel file with Java code, or create an Excel file with Java code? Or do you just have an existing Excel file that you want to automatically open with Excel? Commented May 6, 2015 at 15:50
  • 1
    I want to open an existing file with excel :) Commented May 6, 2015 at 15:58
  • @MiLo Desktop.getDesktop().edit(File path); should do it Commented May 6, 2015 at 15:58
  • will Desktop.getDesktop().open(File path) do the job? Commented May 6, 2015 at 16:02
  • You should use the JavaFX way to do this, not the AWT way. Putting together an answer... Commented May 6, 2015 at 16:03

1 Answer 1

11

The JavaFX way to do this is

File excelFile = new File("/path/to/excel/file");
getHostServices().showDocument(excelFile.toURI().toURL().toExternalForm());

getHostServices() is defined in Application, so if you want to do this in another class (a controller, for example), you will have to arrange for the other class to be able to access the host services.

E.g.

public class MyApp extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        FXMLLoader loader = new FXMLLoader(...);
        Parent root = loader.load();
        MyController controller = loader.getController();
        controller.setHostServices(getHostServices());
        //... setup and show scene and stage...
    }
}

With the obvious method in the controller and the code above suitably modified.

Sign up to request clarification or add additional context in comments.

2 Comments

nice. Didn't know that ther is a javaFx way to open a Document. Thx a lot for that answer!
@James_D this answer works well for loading fxml directly from start method of Application class. But what if we want to use HostServices later in the application? I am a bit new to SO, not sure whether its ok to ask here or I have to ask a separate question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.