JavaFX2.1 - TableView - a TableView content can be exported to Excel

Hi all

I'm new to JavaFx scene, I have a desktop application that uses several of various sizes and values make. When the user closes down the display of the table in question, they asked that the exit of the tableview exported to a csv file in a specified location. I tried various searches but am yet to see examples of if this is still possible in javafx.

Could someone advise if you are able to export content from a TableView to Excel? Pointers would be greatly appreciated.

Thank you.

Here's an example of how export to a csv file:

import javafx.beans.property.SimpleStringProperty;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.beans.value.*;
import javafx.beans.*;
import javafx.beans.property.*;
import javafx.collections.*;

import java.io.*;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.event.EventType;
import javafx.scene.effect.InnerShadow;
import javafx.scene.input.MouseEvent;

public class Tbview extends Application {

    private IntegerProperty index = new SimpleIntegerProperty();

    public final Integer getIndex() {
        return index.get();
    }

    public final void setIndex(Integer value) {
        index.set(value);
    }

    public IntegerProperty indexProperty() {
        return index;
    }

    public static class Person {

        private final SimpleStringProperty firstName;
        private final SimpleStringProperty lastName;
        private final SimpleStringProperty email;

        private Person(String fName, String lName, String email) {
            this.firstName = new SimpleStringProperty(fName);
            this.lastName = new SimpleStringProperty(lName);
            this.email = new SimpleStringProperty(email);
        }

        public String getFirstName() {
            return firstName.get();
        }

        public void setFirstName(String fName) {
            firstName.set(fName);
        }

        public String getLastName() {
            return lastName.get();
        }

        public void setLastName(String fName) {
            lastName.set(fName);
        }

        public String getEmail() {
            return email.get();
        }

        public void setEmail(String fName) {
            email.set(fName);
        }
    }
    private TableView table = new TableView();
    private final ObservableList data =
            FXCollections.observableArrayList(
            new Person("Isabella", "Johnson", "[email protected]"),
            new Person("Ethan", "Williams", "[email protected]"),
            new Person("Emma", "Jones", "[email protected]"),
            new Person("Isabella", "Johnson", "[email protected]"),
            new Person("Ethan", "Williams", "[email protected]"),
            new Person("Emma", "Jones", "[email protected]"),
            new Person("Isabella", "Johnson", "[email protected]"),
            new Person("Ethan", "Williams", "[email protected]"),
            new Person("Emma", "Jones", "[email protected]"),
            new Person("Isabella", "Johnson", "[email protected]"),
            new Person("Ethan", "Williams", "[email protected]"),
            new Person("Emma", "Jones", "[email protected]"),
            new Person("Michael", "Brown", "[email protected]"));

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        Scene scene = new Scene(new Group());
        stage.setTitle("Table View Sample");
        stage.setWidth(400);
        stage.setHeight(500);

        final Label label = new Label("Address Book");
        label.setFont(new Font("Arial", 20));

        final TableColumn firstNameCol = new TableColumn("First Name");
        firstNameCol.setCellValueFactory(
                new PropertyValueFactory("firstName"));

        firstNameCol.setSortable(false);

        firstNameCol.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler() {

            public void handle(MouseEvent event) {

                System.out.println("First name col is pressed");

            }
        });

        TableColumn lastNameCol = new TableColumn("Last Name");
        lastNameCol.setCellValueFactory(
                new PropertyValueFactory("lastName"));
        lastNameCol.setSortable(false);
        TableColumn emailCol = new TableColumn("Email");
        emailCol.setMinWidth(200);
        emailCol.setCellValueFactory(
                new PropertyValueFactory("email"));
        emailCol.setSortable(false);
        table.setItems(data);
        table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
        table.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);

        indexProperty().addListener(new ChangeListener() {

            @Override
            public void changed(ObservableValue o, Object oldVal,
                    Object newVal) {
                table.getSelectionModel().select(index.get());

            }
        });

        // table.getSelectionModel().sel.s.select(1, lastNameCol);

        final VBox vbox = new VBox();
        vbox.setSpacing(5);

        table.onScrollProperty().addListener(new ChangeListener() {

            @Override
            public void changed(ObservableValue observable, Object oldvalue, Object newValue) {
                System.out.println("scror bar " + oldvalue);

            }
        });

        table.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
        table.getSelectionModel().setCellSelectionEnabled(true);

        table.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {

            @Override
            public void changed(ObservableValue observable, Object oldvalue, Object newValue) {
                for (TablePosition t : (ObservableList) table.getSelectionModel().getSelectedCells()) {
                    System.out.println(t.getColumn());
                }
            }
        });

        // table.getSelectionModel().setCellSelectionEnabled(true);

        final Button export = new Button("Export to Excel");
        export.setOnAction(new EventHandler() {

            @Override
            public void handle(ActionEvent e)  {
              try {
                writeExcel();
              }
              catch (Exception ex) {
            ex.printStackTrace();
        }

            }
            //
        });

        vbox.getChildren().addAll(label, table, export);

        vbox.setPadding(new Insets(10, 0, 0, 10));

        ((Group) scene.getRoot()).getChildren().addAll(vbox);
        scene.getStylesheets().add(getClass().getResource("stylesheet.css").toExternalForm());
        stage.setScene(scene);
        stage.show();
    }

    public void writeExcel() throws Exception {
        Writer writer = null;
        try {
            File file = new File("C:\\Person.csv.");
            writer = new BufferedWriter(new FileWriter(file));
            for (Person person : data) {

                String text = person.getFirstName() + "," + person.getLastName() + "," + person.getEmail() + "\n";

                writer.write(text);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        finally {

            writer.flush();
             writer.close();
        }
    }
}

Tags: Java

Similar Questions

  • WebCenter content can be integrated with Oracle iStore or Oracle EBS?

    Hello

    WebCenter content can be integrated with Oracle iStore (as seeds/integration without many glitches/modification) or Oracle EBS as a whole?

    Thanks in advance.

    Srinivas

    Hi Srinivas,

    Yes, ECM can be integrated with Oracle EBS (suite business enterprise) and thus other Oracle applications such as Peoplesoft, Siebel etc..

    Details can be read from the following link: http://docs.oracle.com/cd/E23943_01/doc.1111/e17953/toc.htm

    Thank you
    Srinath

  • content of an export file using the datapump

    How can we see the contents of an export file using the datapump.
    As in the normal exp/imp method, if we use the parameter show = o during import, it displays the script/content of the dump file.

    Is there a method to do this in the datapump method?

    Use the Option SQLFILE

    Directory system/passwd Impdp = directory_name dumpfile = filename.dmp logfile = logfile.log sqlfile = export_scripts.sql full = y

  • can I export my passwords saved to a new PC

    I got a new PC work using Chrome, how can I export my usernames and passwords registered to my new PC

    Google support gives you the steps on how to do

  • Can not export Photos pictures

    My 2008 iMac crashed recently and I just bought an iMac 27 "(10.11.3). I can't export the photos of pictures on my desk. I can import images and view them in Photos, but when I try to export them I get this message: "missing file: cannot open pictures with the unavailable original files." The original photo - is offline or cannot be found. "Click"Find original"reconnect". I just uploaded some 600 photos of Photos over the course of two days (I keep the original RAW files in a different location). I can export some of them, but not the rest. Images uploaded before two days ago seem unaffected. There are occasions when I could not export an image but then later I was able to export the image itself. I use an external hard drive to store my photos. I don't store them on the computer itself. I don't know if it of a problem or not. He has never been in the past.

    I would really appreciate someone to help me with this. Thanks in advance!

    You have a referenced library or managed library (managed with the preference of pictures to copy items imported into the library Photos in his checked default state and is highly recommended)

    LN

  • How can I export images from Photos with Lightroom or Photoshop?

    How can I export images from Photos with Lightroom or Photoshop?

    Use the file ➙ export Original unmodified for Photos X menu option.

  • Can I export the contacts from the phone or MotoBLUR?

    And before you answer - 'of course, copy them to the SIM card"- I want to EXPORT the contacts from the phone.

    I see that I can import contacts on the phone to CSV on the MotoBLUR page, but I can't export.

    I think that there is a demand of "exportcontacts" in the app store - there can be several - which allows you to export the Android contacts to a CSV file on your SD card.

  • Is there a way I can use Microsoft Word, Excel, and Powerpoint on an Android operating system?

    Original title: Android OS

    Is there a way I can use Microsoft Word, Excel, and Powerpoint on an Android operating system?

    Hi DavidBuzzer,

    It is not possible to use Microsoft Word, Excel, and Powerpoint in Android operating system.

    However, you can use your favorite search engine & download any third-party software that could serve the purpose.

    Note: Using third-party software, including hardware drivers can cause serious problems that may prevent your computer from starting properly. Microsoft cannot guarantee that problems resulting from the use of third-party software can be solved. Software using third party is at your own risk.

    Hope the helps of information.

  • How can I export my folders in Outlook Express & save them to my external Hardrive E

    How can I export my folders in Outlook Express & save them to my external Hardrive E

    http://www.insideoe.com/backup/

  • Need help with my Mail window. I can't export my message to the PST format. I keep getting the message error "an error occurred during initialization of MAPI".

    Hello

    Need help with my Mail window. I can't export my message to the PST format. I keep getting the message error "an error occurred during initialization of MAPI". Y at - it solution or another method?

    Hi ErikLee,

    Do you have MS Outlook installed on your computer?

    Windows mail import and export opportunities are limited to an Outlook .pst file or an Exchange Server mailbox. They are available only if MS Outlook is installed.
    If MS Outlook is not installed and you start an import or export action, the necessary support files are not present for Windows mail complete the operation. Then I suggest you to install Outlook temporarily and see if the problem is resolved.

    Follow the instructions below and check if the problem is resolved.

    1. reboot your computer, and then start Windows Mail.
    2. on the Tools menu, click Options.
    3. in the connection tab, click on edit to open the Internet Properties dialog box.
    4. in the tab programs, click on an application other than Windows mail e-mail in the e-mail list. Click on apply and then click OK.
    5. click OK again to close the Options dialog box.
    6. exit Windows mail and restart Windows mail.

    If this does not work, I suggest you upgrade to Windows Live Mail to import or export messages that may help you resolve the issue.

    To download Windows Live Mail, visit the following Microsoft Web site:
    http://get.live.com/wlmail/overview

    For more information about Windows Live Mail, see the Microsoft Web site at the following address:
    http://windowshelp.Microsoft.com/Windows/en-us/help/4b30d3d6-abe2-46d1-a5fd-4a1ba786a1381033.mspx

    Check whether the problem is resolved.

    Please post back and let us know if it helped to solve your problem.

    Kind regards
    KarthiK TP

  • can I export images to my photo gallery for my memory stick card?

    can I export images to my photo gallery for my memory stick card?

    You have a drive internal or external?

    If_Yes_try the following steps...

    Insert the memory card into your Media Player and
    Reach... Start / computer.

    The media player must be recognized as one or
    Most removable disks and each will have a drive
    letter.

    Example:
    Removable disk (e :))
    Removable drive (g)
    Removable disk (h :))

    Left-click each removable disk until you reveal them
    Root directory of the memory card.

    OK... now you know... the drive letter to your
    Image folder... Start / photos.

    If you right-click a selected group of photos or a complete
    You should be able to choose the folder... Send to / removable
    Disk (? :))..) .This must copy the photos on the memory card.

    Make sure that the photos are in one or more records because
    the number of photos that you can copy to the directory root
    will be very limited. And you will receive the following error:

    "Impossible to copy the XXXX: failed to create the directory or file.

    If you prefer to copy Photo Gallery... click right one selected
    Group of photos and choose... Copy. Reach... Start / computer
    Click with the right button on the memory card drive letter and choose
    Dough.

  • How can I export my Contacts from Windows Live Mail

    How can I export my Contacts from Windows Live Mail to pop my ISP e-mail program?  And what is the file format?  Can they be exported to a csv file?

    One of the options when you select export in the file menu and the Contacts folder open is "comma separated values (.)» (CSV).

    -Hope this helps.

    Doug Robbins - Word MVP,
    DKR [atsymbol] MVP [dot] org
    Posted by the community bridge

    "CCarole" wrote in the new message: * e-mail address is removed from the privacy... *

    How can I export my Contacts from Windows Live Mail to pop my ISP e-mail program?  And what is the file format?  Can they be exported to a csv file?

    Doug Robbins - dkr [atsymbol] Word MVP MVP [dot] org

  • BlackBerry Q10 can only export contacts from Q10 to a worksheet?

    How can I export my Contacts from my Q10 in a spreadsheet?

    Hello

    Directly, I don't think you can. According to how you have integrated your contacts, it could be simple or complicated. If you have used the recommended method to use an OTA service (e.g., Outlook.com, GMail, etc.) as the host of your contacts, synchronize your device, then these OTA services may very well have a facility to export you want. Or, if you've been synchronization via LINK to Office Outlook, you can export and then that. If you chose the more dangerous method to only use the device as a unique storage for your critical data platform, while the process is much more difficult... it comes to each synchronization configuration of Office Outlook and then export from there, synchronization with OTA service configuration and export from there , or by using the LINK and make a backup of your device, then find a 3rd party app PC that can translate the backup file owner on your PC for something you can use.

    Sorry to give you so many things, but not knowing the outcome of your configuration in multiple alternative paths.

    Good luck and let us know!

  • If I shoot in 1080/30 p what can I export in 1080/60i?

    If I shoot in 1080/30 p can I export him to 1080/60i?  Thank you!

    Test this would have taken a very short time. And think about this... There are many codec options available some inckude options that you list. PrPro is designed for the export of these options.

    Why wouldn't it here?

    Neil

  • Photoshop 2015.5 can not export the work plan in PNG transparent

    should I upgrade Photoshop to the latest version (2015.5) and now I can not export in PNG transparent work plans and that sucks A * big time
    Anywho whenever I export in PNG or PNG8 with transparrensy, it receives a white background and space color Medallion to the index as if it was a GIF.

    All the solutions or anyone who has a script that will make the transparent PNG out of work plans?

    Are you sure that you correctly configure the work plan? The 2015.5 version to now set the background color of the artboard that is different from before

Maybe you are looking for