import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import java.util.List;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class ExcelDataImport {
// 假设有一个对应Excel表头的Java实体类UserData
public static class UserData {
// 对应表头的字段...
}
public static class ExcelListener extends AnalysisEventListener<UserData> {
private List<UserData> list = new ArrayList<UserData>();
private Connection conn = null;
private PreparedStatement pstmt = null;
public ExcelListener() throws ClassNotFoundException, SQLException {
// 初始化数据库连接
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名", "用户名", "密码");
String sql = "INSERT INTO 表名 (列1, 列2, ...) VALUES (?, ?, ...)";
pstmt = conn.prepareStatement(sql);
}
@Override
public void invoke(UserData data, AnalysisContext context) {
list.add(data);
if (list.size() >= 1000) {
saveData();
list.clear();
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
saveData(); // 保存剩余数据
if (pstmt != null) {
try {
pstmt.executeBatch(); // 执行批量操作
} catch (SQLException e) {
e.printStackTrace();
}
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private void saveData() {
// 执行批量插入
try {
for (UserData userData : list) {
pstmt.setString(1, userData.getField1());
pstmt.setString(2, userData.getField2());
// ...设置其他字段
pstmt.addBatch();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void importExcel(InputStream in) throws ClassNotFoundE
评论已关闭