使用easyExcel导入数据

首先是pom文件引入


        
            com.alibaba
            easyexcel
            3.0.5
        

实体类

package com.biaodian.redis.entity;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.NumberFormat;

import java.io.Serializable;
import java.math.BigDecimal;


public class ExcelEntity implements Serializable {

    @ExcelProperty(value = {"主键id"})
    private Integer id;
    @ExcelProperty(value = {"金额"})
    @NumberFormat("###.##")
    private BigDecimal amount;
    @ExcelProperty(value = {"百分比"})
    @NumberFormat("###.##%")
    private BigDecimal amountRate;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public BigDecimal getAmount() {
        return amount;
    }

    public void setAmount(BigDecimal amount) {
        this.amount = amount;
    }

    public BigDecimal getAmountRate() {
        return amountRate;
    }

    public void setAmountRate(BigDecimal amountRate) {
        this.amountRate = amountRate;
    }
}

监听器,处理excel的数据


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.biaodian.redis.entity.ExcelEntity;
import com.biaodian.redis.service.UserService;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public class ExcelListener extends AnalysisEventListener {

    private UserService userService;

    /**
     * 提供ExcelListener的构造器 注入userService
     * @param userService
     */
    public ExcelListener(UserService userService) {
        this.userService = userService;
    }

    /**
     * 定义接受数据的list
     */
    List list = new ArrayList<>();

    /**
     * 数据是一条一条读取的
     *
     * @param data
     * @param context
     */
    @Override
    public void invoke(ExcelEntity data, AnalysisContext context) {
        list.add(data);
        //这里做了批量插入的操作 所以在 doAfterAllAnalysed方法需要判断list是否为空 不为空的话需要再次插入 防止数据缺失
        if (list.size() == 10) {
            //执行插入操作
            userService.save(list);
            //清理list
            list.clear();
        }
    }

    /**
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        //不为空执行插入操作
        if (!CollectionUtils.isEmpty(list)) {
            //xx.save(list)
            userService.save(list);
            //清理list
            System.out.println(list);
            list.clear();
        }
    }
}

请求接口new ExcelListener(userService)是为了传入注入的service

ExcelEntity.class对应实体类

    @Autowired
    private UserService userService;

    @PostMapping("/importExcel")
    public void importExcel(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        //new ExcelListener(userService) 传入注入的service
        EasyExcel.read(inputStream, ExcelEntity.class, new ExcelListener(userService)).sheet(0).doRead();
    }

你可能感兴趣的:(导出excel,java,easyexcel,导入)