springboot处理excel表格

如果你使用的是 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`方法,每个方法对应一个表。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值