EasyExcel匯入

藝術天分高發表於2020-12-15

記錄摸魚的一天
技術棧:spring boot2.x+mybatis plus+easyExcel 2.2.6

生成簡單的實體類等等等等

匯入easyExcel的依賴

實體類

編寫服務層


import com.csepdi.ledger.model.Information;
import com.baomidou.mybatisplus.extension.service.IService;
import com.github.pagehelper.PageInfo;


import java.util.List;

/**
 * <p>
 *  服務類
 * </p>
 *
 * @author xiaoWan
 * @since 2020-12-10
 */
public interface InformationService extends IService<Information> {

    void readExcel(List<Information> informationList);
}
package com.csepdi.ledger.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csepdi.ledger.model.Information;
import com.csepdi.ledger.mapper.InformationMapper;
import com.csepdi.ledger.service.InformationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服務實現類
 * </p>
 *
 * @author xiaoWan
 * @since 2020-12-10
 */
@Service
public class InformationServiceImpl extends ServiceImpl<InformationMapper, Information> implements InformationService {

    @Autowired
    InformationService informationService;

    @Override
    public void readExcel(List<Information> informationList) {
        informationService.saveBatch(informationList);
    }
}

編寫監聽工具類



import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.csepdi.ledger.model.Information;
import com.csepdi.ledger.service.InformationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

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

@Component
@Scope("prototype")
public class ExcelImportUtils extends AnalysisEventListener<Information> {

    @Autowired
    InformationService informationService;


    List<Information> list = new ArrayList<>();

    @Override
    public void invoke(Information information, AnalysisContext analysisContext) {
        list.add(information);
        informationService.readExcel(list);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    }
}

控制層

    @PostMapping("/importExcel")
    public void importExcel(MultipartFile uploadExcel) throws IOException {
        //工作簿
        ExcelReaderBuilder read = EasyExcel.read(uploadExcel.getInputStream(), Information.class, excelImportUtils);
        //工作表
        read.sheet().doRead();
    }

postman測試

完活

相關文章