微服务 Spring Boot Mybatis-Plus 整合 EasyPOI 实现 Excel 一对多 导入

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

文章目录

⛄引言

Excel导入 是 开发中 很常用的 功能 本篇讲解 如何使用 Spring Boot + MyBatis -Plus 整合 EasyPOI 实现Excel 的一对多导入。

EasyPOI官网

一、EasyPOI 实现Excel 的一对多导入 – 代码实现

⛅需求说明

采用 微服务 Spring Boot、Mybatis-Plus 整合 EasyPOI 实现Excel的一对多导入

Excel 导入 实现详细细节

  • 前端采用 Vue+ElementUI 实现导入页面展示要求弹出上传框展示导入模板、 并且要求文件手动上传
  • 后端导入 要求实现EasyPOI实现、采用工具类完成导入的集合映射
  • 要求使用 Mybatis-Plus 实现 批量导入

⚡核心源码实现

Excel 一对多导入如下所示

在这里插入图片描述

以上的商品信息该如何进行映射呢

EasyPOI为我们提供了专门的映射集合的注解@ExcelCollection

  • 表示一个集合,主要针对一对多的导出,比如一个老师对应多个科目,科目就可以用集合表示

在这里插入图片描述

采用 注解进行映射即可

后端源码

SysUserExcel

package com.chen.excel;

import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelCollection;
import com.chen.entity.GoodsEntity;
import lombok.Data;

import java.util.Date;
import java.util.List;


@Data
public class SysUserExcel {

    @Excel(name = "序号", orderNum = "0", format = "isAddIndex")
    private Integer index = 1;

    @Excel(name = "用户账号 *")
    private String username;

    @Excel(name = "真实姓名 *")
    private String realName;

    @Excel(name = "用户性别 *", replace = {"男_1", "女_2"})
    private Integer gender;

    @Excel(name = "电子邮箱", width = 25)
    private String email;

    @Excel(name = "手机号码 *")
    private String mobile;

    // 注解映射商品信息集合
    @ExcelCollection(name = "商品信息")
    private List<GoodsExcel> goodsList;
}

GoodsExcel

package com.chen.excel;

import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelCollection;
import com.chen.entity.GoodsEntity;
import lombok.Data;

import java.util.List;

@Data
public class GoodsExcel {

    @Excel(name = "商品编号", orderNum = "0", format = "isAddIndex")
    private Integer index = 1;

    @Excel(name = "商品名称")
    private String goodsName;

    @Excel(name = "商品价格")
    private Double goodsPrice;

    @Excel(name = "收货地址")
    private String address;

}

SysUserService

public interface SysUserService extends IService<SysUserEntity> {

    ResultBean<PageInfo<SysUserDTO>> page(SysUserDTO param);

    ResultBean<Integer> insert(SysUserDTO param);

    ResultBean<Integer> importExcel(MultipartFile file);
}

SysUserServiceImpl

@Override
public ResultBean<Integer> importExcel(MultipartFile file) {
    ImportParams importParams = new ImportParams();
    //标题行设置为1行默认是0可以不设置依实际情况设置。
    importParams.setTitleRows(0);
    // 表头设置为1行
    importParams.setHeadRows(2);
    try {
        //读取excel
        List<SysUserExcel> sysUserExcelList = ExcelImportUtil.importExcel(file.getInputStream(), SysUserExcel.class, importParams);

        batchInsert(sysUserExcelList);
        return ResultBean.create(0, "success");
    } catch (Exception e) {
        log.error("导入 Excel 异常 e ==> {}", e);
        return ResultBean.create(10, "导入excel 异常"+e.getMessage());
    }
}

public void batchInsert(List<SysUserExcel> param) throws Exception{
    //1.转换为dto集合
    List<SysUserEntity> sysUserEntityList = BeanUtil.copyToList(param, SysUserEntity.class);
    //2.转换为商品实体集合
    List<GoodsEntity> goodsEntityList = BeanUtil.copyToList(param.get(0).getGoodsList(), GoodsEntity.class);
    //3.转换集合
    sysUserEntityList.stream().filter(obj -> obj.getUsername() != null)
        .forEach(obj -> obj.setPassword("123"));
    //4.批量保存
    saveBatch(sysUserEntityList);
    // 保存用户id至商品id
    sysUserEntityList.stream().forEach(obj -> {
        goodsEntityList.stream().forEach(goods -> {
            goods.setUserId(obj.getId());
        });
    });
    goodsService.saveBatch(goodsEntityList);
}

商品业务类

GoodsEntity

@Data
@TableName("tb_goods")
public class GoodsEntity {

    private Long id;

    private Long userId;

    private String goodsName;

    private Double goodsPrice;

    private String address;

    private Date createTime;

    private Date updateTime;
}

GoodsService

import com.baomidou.mybatisplus.extension.service.IService;
import com.chen.entity.GoodsEntity;

/**
 * @author whc
 */
public interface GoodsService extends IService<GoodsEntity> {

}

GoodsServiceImpl

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.entity.GoodsEntity;
import com.chen.mapper.GoodsMapper;
import com.chen.service.GoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author whc
 */
@Slf4j
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, GoodsEntity> implements GoodsService {

}

前端源码

SysUserList Vue 部分

<el-dialog :visible.sync="userVisibleOnly" width="780px" title="新增/编辑">
    <el-form :model="sysUser" :rules="rules" ref="sysUserForm"  label-width="120px">
        <el-row>
            <el-form-item style="font-weight: bold" label="模板下载">
                <el-button type="text">导入用户模板</el-button>
            </el-form-item>
        </el-row>
        <el-row>
            <el-form-item style="font-weight: bold" label="相关附件">
                <el-upload
                           class="upload-demo"
                           :action="importUrl"
                           :on-success="uploadSuccess"
                           accept=".xlsx"
                           ref="upload"
                           multiple
                           :limit="3"
                           :auto-upload="false"
                           :on-exceed="handleExceed">
                    <el-button type="primary" icon="el-icon-upload2" size="small">导入</el-button>
                </el-upload>
                <!--            <el-button type="primary" size="small">点击上传</el-button>-->
            </el-form-item>
        </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="clkBtnUpload">确定</el-button>
        <el-button type="warning" size="mini" @click="userVisibleOnly = false">取消</el-button>
    </span>
</el-dialog>

SysUserList JS 部分

data(){
	return:{
		userVisibleOnly: false
	}
}
metheds:{
	uploadSuccess(val) {
      if (val.code == 0) {
        this.$message.success("导入成功~");
        this.getSysUserList();
      }
    },
    handleExceed(val) {

    },
    clkBtnUpload() {
      this.submitUpload();
      this.$message({
        showClose: true,
        message: '上传成功正在导入...'
      });
      this.userVisibleOnly = false;
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
}

代码编写完毕进行测试

二、Easy POI 实现一对多导入 – 测试

启动后端、前端 访问 127.0.0.1:80

在这里插入图片描述

导入测试

在这里插入图片描述

导入采用手动导入点击确定后将表单提交至后端

断点进入

在这里插入图片描述

我们看到已经完成了对象映射直接进行映射对象插入数据库即可

扩展知识IDEA 断点快捷键 f8 按行进行断点调试、f9 进入下一次断点位置若没有直接结束

三、效果图展示

在这里插入图片描述

⛵小结

以上就是【Bug 终结者】对 微服务 Spring Boot Mybatis-Plus 整合 EasyPOI 实现 Excel 一对多 导入 的简单介绍Excel一对多导入其实如此简单Excel导入也是很常见的功能希望带来这个案例大家可以遇到需求时进行举一反三感谢支持

如果这篇【文章】有帮助到你希望可以给【Bug 终结者】点个赞👍创作不易如果有对【后端技术】、【前端领域】感兴趣的小可爱也欢迎关注❤️❤️❤️ 【Bug 终结者】❤️❤️❤️我将会给你带来巨大的【收获与惊喜】💝💝💝

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Spring