阅读Excel并将其显示在tableview上。使用2D数组或列表列表填充TableView

时间:2019-06-05 14:31:25

标签: java javafx

我的目的是阅读excel(我可以通过Apache POI读取)并在TableView(JavaFX)上显示excel。我可以在TableView上显示列名,但不能在这些列中填充数据

对于许多可用的资源,我发现了一个通用示例,其中创建了一个单独的类(在该类中初始化了变量,并编写了getter和setter)并通过构造函数值提供给TableView。但就我而言,我无法对这些变量进行硬编码。我不知道TableView将具有的列数时,尝试填充TableView。到目前为止,这是我尝试过的。

package sample;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.scene.control.TableView;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

public class Controller {

    @FXML public TableView tableView;

    public void quitMethod(ActionEvent actionEvent) {
        System.out.println("quit button was pressed");
        System.exit(0);
    }

    public void browseMethod(ActionEvent actionEvent) throws IOException {
        Stage stage = new Stage();

        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Select File");
        fileChooser.setInitialDirectory(new File("C:/"));
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("xls files", "*.xls"),
                new FileChooser.ExtensionFilter("xlsx files", "*.xlsx")
        );
        File file = fileChooser.showOpenDialog(stage);
        String path = file.getPath();
        ArrayList<ArrayList> excel = ReadExcel.main1(path);

        for (int i=0; i<excel.get(0).size();i++) {
            TableColumn<Controller, String> firstcol = new TableColumn<>    (excel.get(0).get(i).toString());
            tableView.getColumns().add(firstcol);
            ObservableList<ArrayList<Controller>> data = FXCollections.observableArrayList(excel.get(i));
            tableView.setItems(data);
        }

    }

}

请有人指导我如何在列中显示数据。 here is what output looks like

1 个答案:

答案 0 :(得分:0)

我创建了一个演示,它解释了当列数未知时如何填充TableView的情况。代码中的注释。

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

/**
 *
 * @author blj0011
 */
public class JavaFXApplication124 extends Application
{
    @Override
    public void start(Stage primaryStage)
    {        
        ObservableList<ObservableList<String>> data = FXCollections.observableArrayList();        
        final List<List<String>> excelData = readExcelFile("fileName.xlsx");//Get data from excel file
        //Add excel data to an observable list
        for(int i = 0; i < excelData.size(); i++)
        {
            data.add(FXCollections.observableArrayList(excelData.get(i)));
        }

        TableView<ObservableList<String>> tableView = new TableView();
        tableView.setItems(data);

        //Create the table columns, set the cell value factory and add the column to the tableview.
        for (int i = 0; i < excelData.get(0).size(); i++) {
            final int curCol = i;
            final TableColumn<ObservableList<String>, String> column = new TableColumn<>(
                    "Col " + (curCol + 1)
            );
            column.setCellValueFactory(
                    param -> new ReadOnlyObjectWrapper<>(param.getValue().get(curCol))
            );
            tableView.getColumns().add(column);
        }

        VBox vbox = new VBox(tableView);

        Scene scene = new Scene(vbox);

        primaryStage.setScene(scene);

        primaryStage.show();

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        launch(args);
    }

    public static List<List<String>> readExcelFile(String fileName)
    {
        List<List<String>> excelContent = new ArrayList();
        int columnCounter = 0;
        int rowCounter = 0;

        try (InputStream inputStream = new FileInputStream(fileName)) {
            DataFormatter formatter = new DataFormatter();

            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0);

            for (Row row : sheet) {
                List<String> tempList = new ArrayList();

                for (Cell cell : row) {
                    String text = formatter.formatCellValue(cell);
                    System.out.print(++columnCounter + ": " + text + " - ");
                    System.out.println(text.length());
                    tempList.add(text.length() == 0 ? "" : text);
                }
                columnCounter = 0;
                excelContent.add(tempList);

                ++rowCounter;
                if (rowCounter == 5) {
                    break;
                }
            }
        }
        catch (IOException | EncryptedDocumentException ex) {
            System.out.println(ex.toString());
        }

        return excelContent;
    }
}

我将不知所措,将此答案归功于@jewelsea。 https://coderanch.com/t/663384/java/Populating-TableView-method