我们在窗口的中间加上TableVie:
在hello-view.fxml的文本中,要增加一些代码。在TableView定义中加上fx:id="TableView1",这样java代码才方便访问,在java代码中要加上@FXML private TableView TableView1;表示定义TableView1这个变量,它关联的是界面上的fx:id="TableView1"的控件。然后我们在单击事件中完善取数并给控件赋值数据的代码,下面我把这两个文件的代码都共享给大家:
hello-view.fxml:
<?xml version="1.0" encoding="UTF-8"?><?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?><BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="899.0" prefWidth="1199.0" xmlns="http://javafx.com/javafx/11.0.14-internal" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.example.demo.HelloController"><top><Pane prefHeight="898.0" prefWidth="1198.0" BorderPane.alignment="CENTER"><children><Button layoutX="386.0" layoutY="46.0" mnemonicParsing="false" onMouseClicked="#openclick1" text="打开文件" /><Button layoutX="492.0" layoutY="46.0" mnemonicParsing="false" text="保存文件" /><TableView fx:id="TableView1" layoutX="8.0" layoutY="100.0" prefHeight="794.0" prefWidth="1171.0"><columns><TableColumn prefWidth="75.0" text="C1" /><TableColumn prefWidth="75.0" text="C2" /></columns></TableView></children></Pane></top>
</BorderPane>
HelloController.java:
package com.example.demo;import javafx.application.Platform;
import javafx.beans.property.SimpleObjectProperty;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.*;
import java.io.File;
import java.time.Duration;
import java.time.Instant;import java.util.HashMap;
import java.util.Map;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.TableColumn;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import javafx.beans.property.SimpleStringProperty;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
//
import javafx.application.Application;
import javafx.scene.Scene;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.ArrayList;public class HelloController {@FXMLprivate TableView TableView1;@FXMLprivate Label welcomeText;@FXMLprotected void openclick2(){}@FXMLprotected void openclick1(){FileChooser fileChooser = new FileChooser();fileChooser.setTitle("文件打开对话框");fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("电子表格", "*.xlsx", "*.xls", "*.ods", "*.txt", "*.csv"));// 设置文件选择框的初始目录(可选)//fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));// 显示文件选择框并获取所选文件File selectedFile = fileChooser.showOpenDialog(new Stage());if (selectedFile != null){String fileName = selectedFile.getName();try {// 使用 Apache POI 读取工作簿Workbook workbook = WorkbookFactory.create(selectedFile);Sheet sheet = workbook.getSheetAt(0); // 假设我们只读取第一个工作表TableView1.getColumns().clear(); // 清除原先的列// 如果没有行或列,直接返回if (sheet.getPhysicalNumberOfRows() == 0 || sheet.getRow(0).getPhysicalNumberOfCells() == 0) {return;}// 创建表头for (int i = 0; i < sheet.getRow(0).getLastCellNum(); i++) {String header = sheet.getRow(0).getCell(i).toString();TableColumn<Map<String, Object>, Object> column = new TableColumn<>(header);final int colIndex = i;column.setCellValueFactory(cellData ->new SimpleObjectProperty<>(cellData.getValue().get(header)));// 判断列是否应显示为日期格式column.setCellFactory(col -> new TextFieldTableCell<>(new CustomStringConverter()));TableView1.getColumns().add(column);}// 创建数据行ObservableList<Map<String, Object>> data = FXCollections.observableArrayList();// 获取列标题Row headerRow = sheet.getRow(0);List<String> headers = new ArrayList<>();for (Cell cell : headerRow) {headers.add(cell.toString());}for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {Row row = sheet.getRow(rowIndex);if (row != null) {Map<String, Object> rowData = new HashMap<>();for (int colIndex = 0; colIndex < headers.size(); colIndex++) {Cell cell = row.getCell(colIndex);if (cell != null) {switch (cell.getCellType()) {case STRING:rowData.put(headers.get(colIndex), cell.getStringCellValue());break;case NUMERIC:if (DateUtil.isCellDateFormatted(cell)) {rowData.put(headers.get(colIndex), cell.getDateCellValue());} else {rowData.put(headers.get(colIndex), cell.getNumericCellValue());}break;case BOOLEAN:rowData.put(headers.get(colIndex), cell.getBooleanCellValue());break;case FORMULA:rowData.put(headers.get(colIndex), cell.getCellFormula());break;case BLANK:rowData.put(headers.get(colIndex), "");break;default:rowData.put(headers.get(colIndex), "不支持的单元格类型");break;}} else {rowData.put(headers.get(colIndex), "");}}data.add(rowData);}}TableView1.setItems(data);workbook.close();} catch (IOException e) {e.printStackTrace();}}}
}
我们运行程序,打开一个电子表格,就能看到电子表中的内容了:样式有点丑,我们以后再调整。