SpringBoot-EasyExcel 操作-导入导出

pom

<!--        EasyExcel 操作Excel-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.1.1</version>
</dependency>
<!--        hutool工具类-->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.15</version>
</dependency>

controller:

@PostMapping({"import"})
public R importExcel(@RequestPart MultipartFile file) throws IOException {
    return this.service.importExcel(file);
}

@GetMapping({"export"})
public void exportExcel(HttpServletResponse response) throws IOException {
    this.service.exportExcel(response);
}

service

/**
 * 导入Excel*/
R importExcel(MultipartFile file) throws IOException;

/**
 *导出Excel */
void exportExcel(HttpServletResponse response) throws IOException;

serviceImpl

@Override
public R importExcel(MultipartFile file) throws IOException {
    //1.验证是否上传的有文件内容
    if(!file.isEmpty()){
        //2.解析 Excel 集合
        List<Content> list= EasyExcel.read(file.getInputStream(),Content.class,null).sheet().doReadSync();
        //3.批量新增
        if(dao.insertBatch(list)>0){
            return R.ok();
        }
    }
    return R.fail();
}

@Override
public void exportExcel(HttpServletResponse response) throws IOException {
    //1.设置为下载
    response.setHeader("Content-Disposition","attachment;filename="+System.currentTimeMillis()+".xlsx");
    //2.查询数据
    List<Content> list=dao.selectAll();
    //3.生成Excel
    EasyExcel.write(response.getOutputStream(), Content.class).sheet().doWrite(list);
}

dao

/**
 * 批量新增数据(MyBatis原生foreach方法)
 * 导入的时候
 */
int insertBatch(List<Content> entities);

mapper,插入数据时使用

<insert id="insertBatch">
    insert into t_content(id,name, title, info, cdate, result, ctime)
    values
    --                动态标签 foreach 循环
    <foreach collection="list" item="entity" separator=",">
        (#{entity.id},#{entity.name}, #{entity.title}, #{entity.info}, #{entity.cdate}, #{entity.result}, #{entity.ctime})
    </foreach>
</insert>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值