如何从xlsx加载数据-javafx

时间:2019-07-05 16:57:04

标签: javafx apache-poi tableview xlsx

有人可以帮助我创建代码吗? 我从Java开始,下一步要在xlsx文件中创建数据。 计划: 当我打开应用程序时,来自xlsx的数据将自动导入到表中。 我要在表格中添加新行,然后将此行添加到xlsx文件中。

控制器:

package sample.Controllers;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import sample.Utils.StopLista;
import java.net.URL;
import java.util.ResourceBundle;


public class StopController implements Initializable {




    @FXML
    private TableView<StopLista> tableView;
    @FXML
    private TableColumn<StopLista, String> dateColumn;
    @FXML
    private TableColumn<StopLista, String> orderColumn;
    @FXML
    private TableColumn<StopLista, String> modelColumn;
    @FXML
    private TableColumn<StopLista, String> changeColumn;
    @FXML
    private TableColumn<StopLista, String> timeColumn;
    @FXML
    private TableColumn<StopLista, String> personColumn;
    @FXML
    private TableColumn<StopLista, String> commentsColumn;


    @FXML
    TextField dateText;
    @FXML
    TextField orderText;
    @FXML
    TextField modelText;
    @FXML
    TextField changeText;
    @FXML
    TextField timeText;
    @FXML
    TextField personText;
    @FXML
    TextField commentsText;

    public StopController() {
    }


    @Override
    public void initialize(URL location, ResourceBundle resources) {
        dateColumn.setCellValueFactory(new PropertyValueFactory<StopLista, String>("data"));
        orderColumn.setCellValueFactory(new PropertyValueFactory<StopLista, String>("zlecenie"));
        modelColumn.setCellValueFactory(new PropertyValueFactory<StopLista, String>("model"));
        changeColumn.setCellValueFactory(new PropertyValueFactory<StopLista, String>("zmiana"));
        timeColumn.setCellValueFactory(new PropertyValueFactory<StopLista, String>("czas"));
        personColumn.setCellValueFactory(new PropertyValueFactory<StopLista, String>("osoba"));
        commentsColumn.setCellValueFactory(new PropertyValueFactory<StopLista, String>("uwagi"));
        tableView.setItems(addList());



        tableView.setEditable(true);
        dateColumn.setCellFactory(TextFieldTableCell.forTableColumn());
        orderColumn.setCellFactory(TextFieldTableCell.forTableColumn());
        modelColumn.setCellFactory(TextFieldTableCell.forTableColumn());
        changeColumn.setCellFactory(TextFieldTableCell.forTableColumn());
        timeColumn.setCellFactory(TextFieldTableCell.forTableColumn());
        personColumn.setCellFactory(TextFieldTableCell.forTableColumn());
        commentsColumn.setCellFactory(TextFieldTableCell.forTableColumn());


    }

    public void addRowToTable() {
        StopLista nowyRekord = new StopLista(dateText.getText(), orderText.getText(), modelText.getText(),
                changeText.getText(), timeText.getText(), personText.getText(), commentsText.getText());
        tableView.getItems().add(nowyRekord);


        dateText.clear();
        orderText.clear();
        modelText.clear();
        changeText.clear();
        timeText.clear();
        personText.clear();
        commentsText.clear();
    }

    public void delateRowTable() {
        ObservableList<StopLista> wybranyRekord, wszystkieRekordy;
        try {
            wszystkieRekordy = tableView.getItems();
            if (wszystkieRekordy.size() != 0) {
                wybranyRekord = tableView.getSelectionModel().getSelectedItems();
                wybranyRekord.forEach(wszystkieRekordy::remove);
            }
        } catch (Exception e) {
            //tabela jest pusta - nic się nie dzieje
        }

    }

    public ObservableList<StopLista> addList() {
        ObservableList<StopLista> orderList = FXCollections.observableArrayList();





        return orderList;
    }

    public void editData(TableColumn.CellEditEvent cellEditEvent){
        StopLista zmDaty = tableView.getSelectionModel().getSelectedItem();
        zmDaty.setData(cellEditEvent.getNewValue().toString());


    }

    public void editOrder(TableColumn.CellEditEvent cellEditEvent){
        StopLista zmZlecenia = tableView.getSelectionModel().getSelectedItem();
        zmZlecenia.setZlecenie(cellEditEvent.getNewValue().toString());


    }

    public void editModel(TableColumn.CellEditEvent cellEditEvent){
        StopLista zmModelu = tableView.getSelectionModel().getSelectedItem();
        zmModelu.setModel(cellEditEvent.getNewValue().toString());


    }

    public void editChange(TableColumn.CellEditEvent cellEditEvent){
        StopLista zmZmiany = tableView.getSelectionModel().getSelectedItem();
        zmZmiany.setZmiana(cellEditEvent.getNewValue().toString());


    }

    public void editTime(TableColumn.CellEditEvent cellEditEvent){
        StopLista zmCzasu = tableView.getSelectionModel().getSelectedItem();
        zmCzasu.setCzas(cellEditEvent.getNewValue().toString());


    }

    public void editPerson(TableColumn.CellEditEvent cellEditEvent){
        StopLista zmOsoby = tableView.getSelectionModel().getSelectedItem();
        zmOsoby.setOsoba(cellEditEvent.getNewValue().toString());


    }

    public void editComments(TableColumn.CellEditEvent cellEditEvent){
        StopLista zmUwag = tableView.getSelectionModel().getSelectedItem();
        zmUwag.setUwagi(cellEditEvent.getNewValue().toString());


    }





}

getter设置程序和控制器

package sample.Utils;

import javafx.beans.property.SimpleStringProperty;

public class StopLista {

    private SimpleStringProperty data, zlecenie, model, zmiana, czas, osoba, uwagi;

    public StopLista(String data, String zlecenie, String model,
                     String zmiana, String czas, String osoba,
                     String uwagi) {
        this.data = new SimpleStringProperty(data);
        this.zlecenie = new SimpleStringProperty(zlecenie);
        this.model = new SimpleStringProperty(model);
        this.zmiana = new SimpleStringProperty(zmiana);
        this.czas = new SimpleStringProperty(czas);
        this.osoba = new SimpleStringProperty(osoba);
        this.uwagi = new SimpleStringProperty(uwagi);
    }

    public String getData() {
        return data.get();
    }

    public SimpleStringProperty dataProperty() {
        return data;
    }

    public void setData(String data) {
        this.data.set(data);
    }

    public String getZlecenie() {
        return zlecenie.get();
    }

    public SimpleStringProperty zlecenieProperty() {
        return zlecenie;
    }

    public void setZlecenie(String zlecenie) {
        this.zlecenie.set(zlecenie);
    }

    public String getModel() {
        return model.get();
    }

    public SimpleStringProperty modelProperty() {
        return model;
    }

    public void setModel(String model) {
        this.model.set(model);
    }

    public String getZmiana() {
        return zmiana.get();
    }

    public SimpleStringProperty zmianaProperty() {
        return zmiana;
    }

    public void setZmiana(String zmiana) {
        this.zmiana.set(zmiana);
    }

    public String getCzas() {
        return czas.get();
    }

    public SimpleStringProperty czasProperty() {
        return czas;
    }

    public void setCzas(String czas) {
        this.czas.set(czas);
    }

    public String getOsoba() {
        return osoba.get();
    }

    public SimpleStringProperty osobaProperty() {
        return osoba;
    }

    public void setOsoba(String osoba) {
        this.osoba.set(osoba);
    }

    public String getUwagi() {
        return uwagi.get();
    }

    public SimpleStringProperty uwagiProperty() {
        return uwagi;
    }

    public void setUwagi(String uwagi) {
        this.uwagi.set(uwagi);
    }
}

有人可以帮助我或演示如何做到吗?

1 个答案:

答案 0 :(得分:1)

我创建了一个演示应用程序,该应用程序使用一个按钮打开一个弹出窗口,允许输入新的Persons。它还演示了如何在没有弹出窗口的情况下进行操作。对于删除,我仅显示一种方法。仅当在表中选择了行时,才可以使用删除按钮从表中删除人。我还喜欢使用所选行上的上下文菜单从表中删除。我没有在这里显示。

  

主要

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

/**
 * JavaFX App
 */
public class App extends Application {
    @Override
    public void start(Stage stage) {
        try {
            Parent root = FXMLLoader.load(App.class.getResource("primary.fxml"));
            Scene scene = new Scene(root);
            stage.setResizable(false);
            stage.setTitle("FXML Welcome");
            stage.setScene(scene);
            stage.show();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

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

控制器

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javafx.beans.binding.Bindings;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class PrimaryController implements Initializable{

    @FXML TableView<Person> tvPerson;
    @FXML TableColumn<Person, String> tcFirstName, tcLastName;
    @FXML Button btnAddNewPerson2;
    @FXML TextField tfFirstName, tfLastName;

    ObservableList<Person> obsPerson = FXCollections.observableArrayList();

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        tcFirstName.setCellValueFactory(new PropertyValueFactory("firstName"));
        tcLastName.setCellValueFactory(new PropertyValueFactory("lastName"));

        List<Person> persons = new ArrayList();
        persons.add(new Person("John", "Doe"));
        persons.add(new Person("Jane", "Doe"));

        obsPerson.addAll(persons);
        tvPerson.setItems(obsPerson);

        //Bind button to the textfields text properties
        btnAddNewPerson2.disableProperty().bind(
            Bindings.isEmpty(tcFirstName.textProperty())
                .or(Bindings.isEmpty(tfLastName.textProperty()))
        );

        btnAddNewPerson2.setOnAction((actionEvent) -> {
            obsPerson.add(new Person(tfFirstName.getText(), tfLastName.getText()));
        });
    }



    @FXML
    private void handleBtnAddNewPerson(ActionEvent event){
        Stage stage = new Stage();

        //Create Nodes to be used in popup
        TextField ltfFirstName = new TextField();
        ltfFirstName.setPromptText("Enter First Name");
        TextField ltfLastName = new TextField();
        ltfLastName.setPromptText("Enter Last Name");
        Button lbtnAddNewPerson = new Button("Add");
        lbtnAddNewPerson.setOnAction((t) -> {
            //Handle updating Excel file and tableview here!
            obsPerson.add(new Person(ltfFirstName.getText(), ltfLastName.getText()));
        });
        lbtnAddNewPerson.requestFocus();//Give this button focus

        //Bind add button to textfield text property
        lbtnAddNewPerson.disableProperty().bind(
            Bindings.isEmpty(ltfFirstName.textProperty())
                .or(Bindings.isEmpty(ltfLastName.textProperty()))
        );
        //Use to cancel
        Button lbtnCancel = new Button("Cancel");
        lbtnCancel.setOnAction((t) -> {
            stage.close();
        });

        VBox root = new VBox(ltfFirstName, ltfLastName, lbtnAddNewPerson, lbtnCancel);
        Scene scene = new Scene(root);

        stage.setResizable(false);
        stage.setTitle("Add New Person");
        stage.setScene(scene);
        stage.initOwner(((Stage)((Button)event.getSource()).getScene().getWindow()));
        stage.showAndWait();
    }

    @FXML
    private void handleBtnDeletePerson(ActionEvent event) {
        if(tvPerson.getSelectionModel().getSelectedItem() != null)
        {
            obsPerson.remove(tvPerson.getSelectionModel().getSelectedItem());
        }
        else{
            Alert alert = new Alert(AlertType.INFORMATION);
            alert.setTitle("Information Dialog");
            alert.setHeaderText("Look, an Information Dialog");
            alert.setContentText("You need to select a Person to delete!");

            alert.showAndWait();
        }
    }
}
  

FXML

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>

<VBox alignment="CENTER" prefHeight="396.0" prefWidth="619.0" spacing="20.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sed.test.mavenfxmltestingground.PrimaryController">
   <children>
      <TableView fx:id="tvPerson" prefHeight="200.0" prefWidth="200.0">
        <columns>
          <TableColumn fx:id="tcFirstName" prefWidth="290.0" text="First Name" />
          <TableColumn fx:id="tcLastName" prefWidth="287.0" text="Last Name" />
        </columns>
      </TableView>
      <Button fx:id="btnAddNewPerson" onAction="#handleBtnAddNewPerson" text="Add New Person" />
      <Button fx:id="btnDeletePerson" mnemonicParsing="false" onAction="#handleBtnDeletePerson" text="Delete Person" />
      <HBox alignment="CENTER" spacing="10.0">
         <children>
            <TextField fx:id="tfFirstName" prefWidth="200.0" />
            <TextField fx:id="tfLastName" prefWidth="200.0" />
            <Button fx:id="btnAddNewPerson2" mnemonicParsing="false" text="Add New Person" />
         </children>
      </HBox>
   </children>
   <padding>
      <Insets bottom="20.0" left="20.0" right="20.0" top="20.0" />
   </padding>
</VBox>