记录摸鱼的一天
技术栈: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();
}