零基础直接上手java跨平台桌面程序,使用javafx(五)TableView显示excel表

我们在窗口的中间加上TableVie:

在hello-view.fxml的文本中,要增加一些代码。在TableView定义中加上fx:id="TableView1",这样java代码才方便访问,在java代码中要加上@FXML private TableView TableView1;表示定义TableView1这个变量,它关联的是界面上的fx:id="TableView1"的控件。然后我们在单击事件中完善取数并给控件赋值数据的代码,下面我把这两个文件的代码都共享给大家:

hello-view.fxml:

XML 复制代码
<?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:

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 {
    @FXML
    private TableView TableView1;
    @FXML
    private Label welcomeText;
    @FXML
    protected void openclick2()
    {



    }

    @FXML
    protected 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();
            }
        }
    }
}

我们运行程序,打开一个电子表格,就能看到电子表中的内容了:样式有点丑,我们以后再调整。

相关推荐
柯南二号6 分钟前
【Java后端】Spring Boot 集成 MyBatis-Plus 全攻略
java·spring boot·mybatis
桦说编程7 小时前
Java 中如何创建不可变类型
java·后端·函数式编程
lifallen7 小时前
Java Stream sort算子实现:SortedOps
java·开发语言
IT毕设实战小研7 小时前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
没有bug.的程序员8 小时前
JVM 总览与运行原理:深入Java虚拟机的核心引擎
java·jvm·python·虚拟机
甄超锋9 小时前
Java ArrayList的介绍及用法
java·windows·spring boot·python·spring·spring cloud·tomcat
阿华的代码王国9 小时前
【Android】RecyclerView复用CheckBox的异常状态
android·xml·java·前端·后端
Zyy~9 小时前
《设计模式》装饰模式
java·设计模式
A尘埃9 小时前
企业级Java项目和大模型结合场景(智能客服系统:电商、金融、政务、企业)
java·金融·政务·智能客服系统
青云交9 小时前
Java 大视界 -- 基于 Java 的大数据可视化在城市交通拥堵治理与出行效率提升中的应用(398)
java·大数据·flink·大数据可视化·拥堵预测·城市交通治理·实时热力图