首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >【java】-swing

【java】-swing

作者头像
贺公子之数据科学与艺术
发布2025-08-29 13:57:27
发布2025-08-29 13:57:27
1730
举报
在这里插入图片描述
在这里插入图片描述

欢迎关注微信公众号:数据科学与艺术 作者WX:superhe199

swing

以下是一个实现你所描述功能的简单例子:

代码语言:javascript
复制
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JButton;
import javax.swing.JFrame;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class MySQLToExcelExporter extends JFrame {
    private JButton exportButton;

    public MySQLToExcelExporter() {
        exportButton = new JButton("Export to Excel");

        exportButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                exportToExcel();
            }
        });

        add(exportButton);

        setSize(300, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public void exportToExcel() {
        String jdbcUrl = "jdbc:mysql://localhost:3306/example?useSSL=false";
        String username = "root";
        String password = "password";

        try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
                Statement statement = connection.createStatement()) {

            String query = "SELECT * FROM my_table WHERE date = CURDATE()";
            ResultSet resultSet = statement.executeQuery(query);

            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet = workbook.createSheet("Data");
            int rowNum = 0;

            while (resultSet.next()) {
                Row row = sheet.createRow(rowNum++);
                Cell cell = row.createCell(0);
                cell.setCellValue(resultSet.getString("field_name"));
            }

            String filePath = "data.xlsx";
            FileOutputStream outputStream = new FileOutputStream(filePath);
            workbook.write(outputStream);
            workbook.close();

            System.out.println("Data exported to " + filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new MySQLToExcelExporter();
    }
}

使用了Apache POI库来操作Excel文件。在导出数据时,只需要将查询结果逐行写入Excel的单元格即可。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-08-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • swing
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档