業務常需將 Excel 數據入庫供報表查詢。本文採用 Apache POI (HSSF 模式,支援 .xls) 解析 Excel,JDBC 連接 DB2 執行批量插入,代碼簡潔可直接用於生產或二次開發。
poi-3.x.jar, poi-ooxml-3.x.jardb2jcc.jar, db2jcc_license_cu.jar (Type 4 驅動)import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class ExcelToDB2Demo {
private static Connection conn = null;
private static Statement stmt = null;
// 1. 連接 DB2 (Type 4 驅動, 無需本地 Client)
private static boolean connectDB2() {
String url = "jdbc:db2://192.168.0.1:50000/dbname";
String user = "username";
String pwd = "password";
try {
Class.forName("com.ibm.db2.jcc.DB2Driver");
conn = DriverManager.getConnection(url, user, pwd);
stmt = conn.createStatement();
return true;
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
return false;
}
}
// 2. 讀取 Excel 並寫入 DB2
private static boolean readExcelToDB2() {
try (FileInputStream fis = new FileInputStream("c:\\test.xls")) {
POIFSFileSystem fs = new POIFSFileSystem(fis);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
int rowNum = sheet.getLastRowNum();
for (int i = 0; i <= rowNum; i++) {
HSSFRow row = sheet.getRow(i);
if (row == null) continue;
String name = row.getCell(0).getStringCellValue();
int id = (int) row.getCell(1).getNumericCellValue();
String sql = "INSERT INTO TEST(ID, NAME) VALUES(" + id + ",'" + name + "')";
stmt.executeUpdate(sql);
}
return true;
} catch (IOException | SQLException e) {
e.printStackTrace();
return false;
}
}
public static void main(String[] args) {
if (connectDB2() && readExcelToDB2()) {
System.out.println("數據導入成功");
} else {
System.out.println("導入失敗");
}
}
}
PreparedStatement 防 SQL 注入並提升批量性能;conn.setAutoCommit(false) 批量提交事務;LOAD 或 INGEST 工具;XSSFWorkbook。