杰瑞科技汇

Java如何通过ODBC连接Excel?

Of course! Connecting to an Excel file from Java using ODBC is a classic approach, though it's now considered a legacy method. I'll provide a complete guide covering the setup, the Java code, and a modern alternative.

Java如何通过ODBC连接Excel?-图1
(图片来源网络,侵删)

Overview: The ODBC Approach for Java and Excel

This method involves two main parts:

  1. On your Windows machine: You configure an ODBC Data Source Name (DSN) that tells Windows how to talk to your Excel file.
  2. In your Java code: You use standard JDBC (Java Database Connectivity) to connect to that DSN, treating the Excel file like a simple database.

Important Considerations:

  • Windows Only: ODBC is a Windows technology. This method will not work on macOS or Linux.
  • Legacy: Microsoft has deprecated the Microsoft Excel Driver for ODBC. While it still works on modern Windows systems, it's not the recommended approach for new projects.
  • 64-bit vs. 32-bit: You must ensure your Java version (32-bit or 64-bit) matches your ODBC Data Source Administrator (32-bit or 64-bit). This is a very common source of errors.

Part 1: Setting Up the ODBC Data Source (DSN)

Let's assume you have an Excel file named data.xlsx located at C:\temp\data.xlsx. This file has a sheet named Sheet1 with the following data:

ID Name City
1 Alice New York
2 Bob London
3 Carol Paris

Step 1: Open ODBC Data Source Administrator

  1. Press the Windows Key, type ODBC, and select "Set up ODBC data sources".
  2. You will see two versions: a 32-bit and a 64-bit version. You must choose the one that matches your Java installation's architecture.
    • How to check your Java version? Open a command prompt and run: java -version. Look for "x86" (32-bit) or "amd64" (64-bit).
    • Recommendation: For modern systems, use the 64-bit version.

Step 2: Create a New DSN

  1. In the ODBC Data Source Administrator window, go to the "User DSN" or "System DSN" tab. "System DSN" is generally preferred as it's available to all users on the system.

    Java如何通过ODBC连接Excel?-图2
    (图片来源网络,侵删)
  2. Click the "Add..." button.

  3. From the list of drivers, select "Microsoft Excel Driver (.xls, .xlsx, .xlsm, .xlsb)" and click "Finish".

  4. You will see the ODBC Microsoft Excel Setup window.

    • Data Source Name: Give your connection a name, for example, ExcelDSN.
    • Description (Optional): Add a description like "My Excel Data Source".
    • Select Workbook: Click the "Select..." button and navigate to your Excel file (C:\temp\data.xlsx). Click OK.
    • Excel Version: The driver will usually detect this automatically. Ensure it matches your file (e.g., Excel 2007-2025 XML).
    • Sheet Options:
      • Select "Sheet1$" from the "Name" dropdown. The signifies it's a worksheet.
      • Crucially, check the box for "Read Data from the First Row of the Range". This tells the driver to use the first row of your sheet as column names.
  5. Click "OK". Your new DSN "ExcelDSN" will now appear in the list. Click "OK" again to close the ODBC Administrator.

    Java如何通过ODBC连接Excel?-图3
    (图片来源网络,侵删)

Part 2: The Java Code

Now you can write Java code to connect to this DSN.

Prerequisites

You don't need any external libraries for the connection itself, as the JDBC-ODBC bridge (sun.jdbc.odbc.JdbcOdbcDriver) was included in older Java versions. However, this bridge is deprecated and removed from Java 8 and later.

For modern Java (8+), you need a third-party JDBC driver that can connect to ODBC data sources. The most common one is JDBC-ODBC Bridge from third parties.

A popular choice is the JDBC-ODBC Bridge from UCanAccess or other open-source projects. For simplicity, let's assume you are using a modern bridge library. You would typically add a dependency like this to your Maven pom.xml:

<!-- Example for a hypothetical JDBC-ODBC bridge driver -->
<dependency>
    <groupId>com.example</groupId>
    <artifactId>jdbc-odbc-bridge</artifactId>
    <version>1.0.0</version>
</dependency>

(Note: Finding a maintained, modern JDBC-ODBC bridge can be difficult. This is why the JPA approach is often better.)

Java Code Example

Here is a complete, runnable Java example.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ReadExcelWithODBC {
    public static void main(String[] args) {
        // The DSN name you created in the ODBC Administrator
        String dsnName = "ExcelDSN";
        // The connection URL format for the JDBC-ODBC Bridge
        // NOTE: The "sun.jdbc.odbc.JdbcOdbcDriver" is deprecated and will not work on Java 8+.
        // You need a modern JDBC-ODBC bridge driver.
        String url = "jdbc:odbc:" + dsnName;
        // The query to select data from the Excel sheet
        // Note: Sheet names are enclosed in square brackets [ ] in the query.
        String sql = "SELECT ID, Name, City FROM [Sheet1$]";
        // Using a try-with-resources statement to ensure resources are closed automatically
        try (Connection connection = DriverManager.getConnection(url);
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(sql)) {
            System.out.println("Connection to Excel via ODBC successful!");
            System.out.println("--------------------------------------------------");
            // Loop through the result set and print the data
            while (resultSet.next()) {
                // Retrieve by column name for robustness
                int id = resultSet.getInt("ID");
                String name = resultSet.getString("Name");
                String city = resultSet.getString("City");
                System.out.printf("ID: %d, Name: %s, City: %s%n", id, name, city);
            }
        } catch (SQLException e) {
            System.err.println("SQL Error occurred:");
            e.printStackTrace();
        }
    }
}

Part 3: The Modern Alternative (Recommended)

Using ODBC is cumbersome and outdated. The standard, modern, and cross-platform way to read Excel files in Java is by using a dedicated library like Apache POI.

Why Apache POI is Better:

  • Cross-Platform: Works on Windows, macOS, and Linux.
  • No Configuration: You don't need to set up any ODBC drivers or DSNs.
  • More Features: You can read formulas, styles, images, and write back to Excel files, which is very difficult with ODBC.
  • Active Development: It's a well-maintained, open-source project from the Apache Software Foundation.

Example with Apache POI

First, add the Maven dependency to your pom.xml:

<dependencies>
    <!-- For Excel 2007+ (.xlsx) -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.2.3</version> <!-- Use the latest version -->
    </dependency>
</dependencies>

Now, here is the Java code to read the same file:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadExcelWithPOI {
    public static void main(String[] args) {
        // Path to the Excel file
        String excelFilePath = "C:\\temp\\data.xlsx";
        // Use try-with-resources to automatically close the file stream and workbook
        try (FileInputStream fis = new FileInputStream(excelFilePath);
             Workbook workbook = new XSSFWorkbook(fis)) {
            System.out.println("Reading Excel file with Apache POI...");
            System.out.println("--------------------------------------------------");
            // Get the first sheet from the workbook
            Sheet sheet = workbook.getSheetAt(0); // Or sheet.getSheet("Sheet1");
            // Get the first row (header row)
            Row headerRow = sheet.getRow(0);
            // Iterate through the rest of the rows (data rows)
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row != null) {
                    // Get cells by column index (0-based)
                    // It's good practice to check if a cell is null
                    Cell idCell = row.getCell(0);
                    Cell nameCell = row.getCell(1);
                    Cell cityCell = row.getCell(2);
                    int id = (int) idCell.getNumericCellValue();
                    String name = nameCell.getStringCellValue();
                    String city = cityCell.getStringCellValue();
                    System.out.printf("ID: %d, Name: %s, City: %s%n", id, name, city);
                }
            }
        } catch (IOException e) {
            System.err.println("Error reading the Excel file:");
            e.printStackTrace();
        }
    }
}

Summary: ODBC vs. Apache POI

Feature Java ODBC Apache POI
Platform Windows Only Cross-Platform (Windows, macOS, Linux)
Setup Complex (Requires ODBC DSN configuration) Simple (Just add a Maven dependency)
Read/Write Read-only is easy. Writing is complex. Full read and write capabilities.
Data Fidelity Treats Excel as a table; loses formatting. Can read and write formulas, styles, images.
Recommendation Legacy. Avoid for new projects. Standard. The recommended approach.
分享:
扫描分享到社交APP
上一篇
下一篇