專案需求單純:讀取 Excel → 寫入 DB2 → 報表展示。對比 JXL、POI 等方案,POI 出身 Apache、社群活躍、支援 .xls/.xlsx、API 成熟,最終選定 POI 3.x(HSSF/XSSF)。
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<!-- DB2 JDBC Type 4 驅動 -->
<dependency>
<groupId>com.ibm.db2</groupId>
<artifactId>db2jcc4</artifactId>
<version>10.5</version>
</dependency>
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelToDB2Importer {
private static final String JDBC_URL = "jdbc:db2://192.168.0.1:50000/DBNAME";
private static final String USER = "username";
private static final String PASS = "password";
private static final String EXCEL_PATH = "c:/test.xlsx";
private static final String INSERT_SQL = "INSERT INTO TEST (ID, NAME) VALUES (?, ?)";
public static void main(String[] args) {
try (Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(INSERT_SQL);
FileInputStream fis = new FileInputStream(EXCEL_PATH);
Workbook wb = WorkbookFactory.create(fis)) {
Sheet sheet = wb.getSheetAt(0);
conn.setAutoCommit(false); // 批量提交
for (Row row : sheet) {
if (row.getRowNum() == 0) continue; // 跳過標題列
Cell idCell = row.getCell(0);
Cell nameCell = row.getCell(1);
if (idCell == null || nameCell == null) continue;
int id = (int) idCell.getNumericCellValue();
String name = nameCell.getStringCellValue();
ps.setInt(1, id);
ps.setString(2, name);
ps.addBatch();
// 每 1000 條提交一次,避免日誌暴漲
if (row.getRowNum() % 1000 == 0) {
ps.executeBatch();
conn.commit();
}
}
ps.executeBatch(); // 餘數提交
conn.commit();
System.out.println("資料導入成功");
} catch (IOException | SQLException e) {
e.printStackTrace();
System.err.println("導入失敗:" + e.getMessage());
}
}
private static Connection getConnection() throws SQLException {
try {
Class.forName("com.ibm.db2.jcc.DB2Driver"); // Type 4 純 Java 驅動
} catch (ClassNotFoundException e) {
throw new SQLException("找不到 DB2 JDBC 驅動", e);
}
return DriverManager.getConnection(JDBC_URL, USER, PASS);
}
}
com.ibm.db2.jcc.DB2Driver 純 Java、無需 Client 安裝、跨平台部署最簡單。ClassNotFoundException:確認 db2jcc4.jar 在 Classpath。-Dfile.encoding=UTF-8。NumericCellValue 取得 double,轉 long 或 BigDecimal 處理。DateUtil.isCellDateFormatted(cell) 判斷,再 getDateCellValue()。