将swing表格数据导出到excel表格

木子空间Pro 2023-08-18 22:27:40

依赖

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>5.0.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.0.0</version>
    </dependency>

示例代码

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.swing.*;
import java.io.FileOutputStream;
import java.io.IOException;

public class SwingTableToExcelExporter {
    public static void exportToExcel(JTable table, String filePath) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        // 获取表格模型
        TableModel tableModel = table.getModel();

        // 创建表头行
        Row headerRow = sheet.createRow(0);
        for (int col = 0; col < tableModel.getColumnCount(); col++) {
            Cell cell = headerRow.createCell(col);
            cell.setCellValue(tableModel.getColumnName(col));
        }

        // 填充数据行
        for (int row = 0; row < tableModel.getRowCount(); row++) {
            Row dataRow = sheet.createRow(row + 1);
            for (int col = 0; col < tableModel.getColumnCount(); col++) {
                Cell cell = dataRow.createCell(col);
                Object cellValue = tableModel.getValueAt(row, col);
                if (cellValue != null) {
                    cell.setCellValue(cellValue.toString());
                }
            }
        }

        try (FileOutputStream fileOut = new FileOutputStream(filePath)) {
            workbook.write(fileOut);
        }

        workbook.close();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JTable table = new JTable();

                // 添加表格数据

                String filePath = "C:/path/to/output.xlsx";

                try {
                    exportToExcel(table, filePath);
                    JOptionPane.showMessageDialog(null, "导出成功!");
                } catch (IOException e) {
                    JOptionPane.showMessageDialog(null, "导出失败:" + e.getMessage());
                }
            }
        });
    }
}
...全文
673 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

14

社区成员

发帖
与我相关
我的任务
社区描述
学习交流,在线答疑,远程协助,程序定制与DIY,直接私聊群主即可,忙碌时段回复有延迟!
后端经验分享程序人生 个人社区 广东省·广州市
社区管理员
  • 木子空间Pro
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧