ResultSet导出到execl表格

木子空间Pro 2024-01-12 11:13:22

必要依赖包:

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.33</version>
        </dependency>
        <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>

方法封装:

参数:结果集,表头

package com.DormCheck.utils;

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

import javax.swing.*;
import java.io.FileOutputStream;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

public class ExcelExporter {
    public static void exportToExcel(ResultSet resultSet, String[] headers) {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("xxxx");

            // 创建表头行
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 获取结果集元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();

            // 遍历结果集
            int rowIndex = 1;
            while (resultSet.next()) {
                Row row = sheet.createRow(rowIndex++);
                for (int i = 1; i <= columnCount; i++) {
                    Cell cell = row.createCell(i - 1);
                    Object value = resultSet.getObject(i);
                    if (value != null) {
                        cell.setCellValue(value.toString());
                    }
                }
            }

            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }
            // 保存Excel文件
            try (FileOutputStream outputStream = new FileOutputStream("xxxx.xlsx")) {
                workbook.write(outputStream);
            }
            JOptionPane.showMessageDialog(null,"导出成功");
            System.out.println("导出成功!");
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,"导出失败:" + e.getMessage());
            System.out.println("导出失败:" + e.getMessage());
        }
    }
}
...全文
138 回复 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

14

社区成员

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

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