杰瑞科技汇

Java如何连接MySQL并导出Excel数据?

Of course! The combination of Java, MySQL, and Excel is a very powerful and common stack for data processing, reporting, and automation. Here’s a comprehensive guide covering the core concepts, popular libraries, and a complete, practical example.

Java如何连接MySQL并导出Excel数据?-图1
(图片来源网络,侵删)

The Big Picture: Why Use This Stack?

This stack is typically used for data-driven applications. Here’s a common workflow:

  1. Data Storage: Information is stored long-term in a MySQL database.
  2. Business Logic: A Java application processes this data. This could involve calculations, filtering, data transformation, or complex business rules.
  3. Data Output/Reporting: The processed data needs to be presented to a user. Excel is the de facto standard for this due to its familiarity, formatting capabilities, and ease of use.

Example Use Cases:

  • Monthly Sales Report: A Java app queries a MySQL database for sales data from the last month, performs calculations (e.g., total sales, per-product breakdown), and generates a formatted Excel report.
  • Data Import/Export Tool: An admin can upload an Excel file containing new customer data. A Java app reads the Excel file, validates it, and inserts the records into the MySQL database. The reverse process (exporting data to Excel) is equally common.
  • Automated Dashboard: A Java backend runs periodically, fetches the latest data from MySQL, and updates a data source for a front-end dashboard. Excel can be used as an intermediate step for manual review or one-off analysis.

Core Components and Libraries

You'll need specific libraries to bridge the gap between Java and the other two technologies.

A. Java & MySQL: JDBC (Java Database Connectivity)

JDBC is the standard Java API for connecting to relational databases like MySQL. It's built into the Java Development Kit (JDK).

Java如何连接MySQL并导出Excel数据?-图2
(图片来源网络,侵删)

Key Library:

  • MySQL Connector/J: This is the JDBC driver for MySQL. It acts as a bridge, allowing your Java code to communicate with the MySQL database.

How to get it:

  • Maven: Add this to your pom.xml:
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.0.33</version> <!-- Use the latest version -->
    </dependency>
  • Gradle: Add this to your build.gradle:
    implementation 'com.mysql:mysql-connector-j:8.0.33' // Use the latest version

B. Java & Excel: Apache POI

Apache POI (Poor Obfuscation Implementation) is the most popular and powerful Java library for working with Microsoft Office files, including Excel.

Key Libraries:

  • POI for .xls (Legacy Excel format):
    • poi: Core library.
  • POI for .xlsx (Modern Excel format):
    • poi-ooxml: Required for .xlsx, .xlsm, etc.
    • poi-ooxml-lite: A lighter version if you only need to read/write.

How to get it (Maven):

<!-- For modern .xlsx files -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.3</version> <!-- Use the latest version -->
</dependency>

Step-by-Step Practical Example: Data Export to Excel

Let's build a complete Java application that connects to a MySQL database, reads data, and writes it to an Excel file.

Step 1: Prerequisites

  1. Java Development Kit (JDK): Version 8 or newer.

  2. MySQL Server: A running MySQL instance.

  3. MySQL Database and Table: Create a sample database and table.

    CREATE DATABASE company_db;
    USE company_db;
    CREATE TABLE employees (
        id INT AUTO_INCREMENT PRIMARY KEY,
        first_name VARCHAR(50) NOT NULL,
        last_name VARCHAR(50) NOT NULL,
        department VARCHAR(50),
        salary DECIMAL(10, 2),
        hire_date DATE
    );
    INSERT INTO employees (first_name, last_name, department, salary, hire_date) VALUES
    ('John', 'Doe', 'Engineering', 90000.00, '2025-01-15'),
    ('Jane', 'Smith', 'Marketing', 75000.00, '2025-03-22'),
    ('Peter', 'Jones', 'Engineering', 110000.00, '2025-07-10'),
    ('Mary', 'Williams', 'HR', 65000.00, '2025-05-30');

Step 2: Set up your Java Project

  1. Create a new Maven project in your favorite IDE (IntelliJ, Eclipse, VS Code).
  2. Add the mysql-connector-j and poi-ooxml dependencies to your pom.xml file as shown in section 2.

Step 3: The Java Code (ExcelExporter.java)

This class will handle the entire process.

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ExcelExporter {
    // --- Database Connection Details ---
    private static final String DB_URL = "jdbc:mysql://localhost:3306/company_db?useSSL=false&serverTimezone=UTC";
    private static final String DB_USER = "root"; // Your MySQL username
    private static final String DB_PASSWORD = "your_password"; // Your MySQL password
    public static void main(String[] args) {
        String excelFilePath = "employees_report.xlsx";
        // 1. Fetch data from MySQL
        List<Employee> employees = fetchEmployeesFromDatabase();
        // 2. Write data to Excel file
        if (employees != null && !employees.isEmpty()) {
            writeEmployeesToExcel(employees, excelFilePath);
            System.out.println("Excel file '" + excelFilePath + "' has been created successfully.");
        } else {
            System.out.println("No data to export.");
        }
    }
    /**
     * Connects to the MySQL database and retrieves employee data.
     */
    private static List<Employee> fetchEmployeesFromDatabase() {
        List<Employee> employees = new ArrayList<>();
        String sql = "SELECT id, first_name, last_name, department, salary, hire_date FROM employees";
        // Using try-with-resources to ensure connections are closed automatically
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            while (rs.next()) {
                int id = rs.getInt("id");
                String firstName = rs.getString("first_name");
                String lastName = rs.getString("last_name");
                String department = rs.getString("department");
                double salary = rs.getDouble("salary");
                Date hireDate = rs.getDate("hire_date");
                employees.add(new Employee(id, firstName, lastName, department, salary, hireDate));
            }
        } catch (SQLException e) {
            System.err.println("Database error: " + e.getMessage());
            e.printStackTrace();
            return null; // Indicate failure
        }
        return employees;
    }
    /**
     * Creates an Excel file and writes the list of employees into it.
     */
    private static void writeEmployeesToExcel(List<Employee> employees, String excelFilePath) {
        // Using try-with-resources for Workbook and FileOutputStream
        try (Workbook workbook = new XSSFWorkbook()) { // Use XSSFWorkbook for .xlsx
            Sheet sheet = workbook.createSheet("Employees");
            // Create a header row
            Row headerRow = sheet.createRow(0);
            String[] headers = {"ID", "First Name", "Last Name", "Department", "Salary", "Hire Date"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }
            // Create data rows
            int rowNum = 1;
            for (Employee employee : employees) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(employee.getId());
                row.createCell(1).setCellValue(employee.getFirstName());
                row.createCell(2).setCellValue(employee.getLastName());
                row.createCell(3).setCellValue(employee.getDepartment());
                row.createCell(4).setCellValue(employee.getSalary());
                row.createCell(5).setCellValue(employee.getHireDate().toString()); // Simple date format
            }
            // Auto-size columns for better readability
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }
            // Write the workbook to a file
            try (FileOutputStream fileOut = new FileOutputStream(excelFilePath)) {
                workbook.write(fileOut);
            }
        } catch (IOException e) {
            System.err.println("Error writing to Excel file: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
/**
 * A simple POJO (Plain Old Java Object) to represent an Employee.
 */
class Employee {
    private int id;
    private String firstName;
    private String lastName;
    private String department;
    private double salary;
    private Date hireDate;
    // Constructor, Getters, and Setters
    public Employee(int id, String firstName, String lastName, String department, double salary, Date hireDate) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.department = department;
        this.salary = salary;
        this.hireDate = hireDate;
    }
    public int getId() { return id; }
    public String getFirstName() { return firstName; }
    public String getLastName() { return lastName; }
    public String getDepartment() { return department; }
    public double getSalary() { return salary; }
    public Date getHireDate() { return hireDate; }
}

Step 4: Run the Application

  1. Update the DB_USER and DB_PASSWORD in the code with your MySQL credentials.
  2. Run the main method in ExcelExporter.java.
  3. After execution, you will find a new file named employees_report.xlsx in your project's root directory. Open it, and you'll see the employee data neatly formatted.

Going Further: Reading from Excel

The process is just the reverse. You read an Excel file and use JDBC to insert the data into MySQL.

Conceptual Code Snippet:

// 1. Open Excel file
try (Workbook workbook = WorkbookFactory.create(new File("employees_to_import.xlsx"));
     Sheet sheet = workbook.getSheetAt(0)) {
    // 2. Iterate over rows (skip header row)
    for (Row row : sheet) {
        if (row.getRowNum() == 0) continue; // Skip header
        String firstName = row.getCell(1).getStringCellValue();
        String lastName = row.getCell(2).getStringCellValue();
        // ... get other cell values
        // 3. Prepare and execute SQL INSERT statement
        String sql = "INSERT INTO employees (first_name, last_name, department, salary, hire_date) VALUES (?, ?, ?, ?, ?)";
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, firstName);
            pstmt.setString(2, lastName);
            // ... set other parameters
            pstmt.executeUpdate();
        }
    }
}

Best Practices and Advanced Topics

  1. Connection Pooling: For high-performance applications, don't create a new database connection for every query. Use a connection pool library like HikariCP or Apache Commons DBCP. It manages a cache of connections, dramatically improving performance.
  2. Error Handling and Transactions: Wrap your database operations in transactions (conn.setAutoCommit(false)). If any part of the operation fails, you can roll back (conn.rollback()) to prevent a partial, inconsistent state in your database.
  3. Advanced Excel Features:
    • Styling: Use CellStyle to change fonts, colors, borders, and add number formats (e.g., for currency).
    • Formulas: You can write formulas directly into cells using cell.setCellFormula("SUM(A1:A10)").
    • Large Files: For very large Excel files, use the SXSSF (Streaming API) from Apache POI to avoid running out of memory. It writes rows to disk as they are processed.
  4. Configuration: Don't hardcode database credentials or file paths in your code. Use external configuration files (e.g., config.properties) or environment variables.
分享:
扫描分享到社交APP
上一篇
下一篇