阅读Excel并将其显示在tableview上.使用2D数组或列表列表填充TableView [英] Read Excel and show it on tableview. Populate TableView using 2D array or List of List

查看:95
本文介绍了阅读Excel并将其显示在tableview上.使用2D数组或列表列表填充TableView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My aim is to read the excel (which I am able to, via Apache POI) and display the excel on TableView (JavaFX). I am able to display column names on TableView, but not able to fill data in these columns

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

For many resources available I found, a general example where a separate class is created (in which variable are initialized, getters and setters are written) and through constructor values are supplied to TableView. But in my case, I cannot hard code these variables. I am trying to populate a TableView when knowing the number of columns that the TableView will have is not known. Here is what I have tried so far.

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);
        }

    }

}

请有人指导我如何在列中显示数据. 这是输出的样子

Someone please guide me on how to display data in columns. here is what output looks like

推荐答案

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

I have created a demo that explains how to populate a TableView when the number of columns is unknown. Comments in the code.

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-方法

I am going to go out on a limb and credit this answer to @jewelsea. https://coderanch.com/t/663384/java/Populating-TableView-method

这篇关于阅读Excel并将其显示在tableview上.使用2D数组或列表列表填充TableView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆