如果你使用的是 MyBatis-Plus,你可以使用它提供的`ExcelUtil`工具类来读取 Excel 文件并将数据保存到数据库中。以下是示例代码:1. 在 pom.xml 中添加 MyBatis-Plus 和 Easy Excel 的依赖:
```xml
<!-- MyBatis-Plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</dependency>
<!-- Easy Excel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.10</version>
</dependency>
```
2. 在 Controller 中添加 POST 请求处理方法:
```java
@PostMapping("/excel")
public String uploadExcel(@RequestParam("file") MultipartFile file) throws IOException {
InputStream inputStream = file.getInputStream();
ExcelReader excelReader = new ExcelReader(inputStream, null, new ExcelListener());
excelReader.read();
excelReader.finish();
return "success";
}
```
3. 定义 ExcelListener 类来处理 Excel 文件中的数据:```java
public class ExcelListener extends AnalysisEventListener<User> {
private List<User> userList = new ArrayList<>();
@Override
public void invoke(User user, AnalysisContext analysisContext) {
userList.add(user);
if (userList.size() >= 1000) {
// 每读取 1000 条数据,就调用一次 saveBatch 方法保存到数据库中
saveBatch(userList);
userList.clear();
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
// 最后剩余的数据也要保存到数据库中
saveBatch(userList);
}
private void saveBatch(List<User> userList) {
// 使用 MyBatis-Plus 提供的 Service 类来操作数据库
UserService userService = new UserServiceImpl();
userService.saveBatch(userList);
}
}
```
在上面的代码中,我们使用 Easy Excel 提供的`AnalysisEventListener`来读取 Excel 文件中的数据。每当读取到一行数据时,就将其存储到一个`List`对象中。当`List`对象中的数据达到 1000
当`List`对象中的数据达到 1000 条时,我们调用`saveBatch`方法将数据保存到数据库中,并清空`List`对象,以便继续读取下一批数据。在`doAfterAllAnalysed`方法中,我们也需要将剩余的数据保存到数据库中,因为`invoke`方法可能无法达到 1000 条数据的要求。这里再给出`saveBatch`方法的实现代码,供参考:
```java
private void saveBatch(List<User> userList) {
userService.saveBatch(userList);
}
```
在这个示例中,我们使用了 MyBatis-Plus 提供的`saveBatch`方法来将数据保存到数据库中。如果你需要将数据保存到多个表中,你可以实现多个`saveBatch`方法,每个方法对应一个表。