0
点赞
收藏
分享

微信扫一扫

【java】-swing

求阙者 04-16 22:45 阅读 3

(目录)

swing

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

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的单元格即可。

举报

相关推荐

0 条评论