零基础直接上手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 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 {
    @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();
            }
        }
    }
}

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

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Kotlin中使用JavaFX开发跨平台桌面应用程序主要需要以下步骤: 1. 安装JavaFXJavaFXJava平台的一个GUI框架,可以用于创建丰富的桌面应用程序。在Kotlin中使用JavaFX,需要先安装JavaFX。可以从Oracle官网下载JavaFX SDK,或者从Maven仓库中获取。 2. 配置开发环境:配置Kotlin和JavaFX的开发环境,使得Kotlin代码能够访问JavaFX库。在IntelliJ IDEA中,可以通过添加JavaFX SDK的路径来配置JavaFX的开发环境。 3. 创建JavaFX应用程序使用Kotlin编写JavaFX应用程序,可以使用JavaFX的API,以及Kotlin的语法和特性。在Kotlin中创建JavaFX应用程序的方式和在Java中创建JavaFX应用程序的方式类似。 4. 编译和打包应用程序使用Kotlin编写的JavaFX应用程序可以编译为Java字节码,然后打包为可执行文件。可以使用Maven或Gradle来管理项目,构建和打包应用程序。 下面是一个使用Kotlin和JavaFX开发桌面应用程序的示例代码: ```kotlin import javafx.application.Application import javafx.scene.Scene import javafx.scene.control.Button import javafx.scene.layout.StackPane import javafx.stage.Stage class HelloWorld : Application() { override fun start(primaryStage: Stage?) { val button = Button("Hello World") button.setOnAction { println("Hello World") } val root = StackPane() root.children.add(button) val scene = Scene(root, 300.0, 250.0) primaryStage?.title = "Hello World" primaryStage?.scene = scene primaryStage?.show() } } fun main(args: Array<String>) { Application.launch(HelloWorld::class.java, *args) } ``` 这个应用程序创建了一个窗口,包含一个按钮,点击按钮时会在控制台输出"Hello World"。可以使用Kotlin编译器编译这个应用程序,并打包为可执行文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值