使用EasyExcel进行导入数据有好多种方法,详情见https://www.yuque.com/easyexcel/doc
这里使用的是用监听器完成导入.
1.首先我们创建一个监听器,来进行读取数据并存入数据库
public class BzhdSystemConstructionImportListener extends AnalysisEventListener{ private static final Logger LOGGER = LoggerFactory.getLogger(BzhdSystemConstructionImportListener.class); private static final int BATCH_COUNT = 5; List list = new ArrayList (); private BzhdSystemConstructionMapper bzhdSystemConstructionMapper; public BzhdSystemConstructionImportListener(BzhdSystemConstructionMapper bzhdSystemConstructionMapper) { this.bzhdSystemConstructionMapper = bzhdSystemConstructionMapper; } @Override public void invoke(BzhdSystemConstructionImport bzhdSystemConstructionImport, AnalysisContext analysisContext) { LOGGER.info("解析到一条数据:{}", JSON.toJSONString(bzhdSystemConstructionImport)); list.add(bzhdSystemConstructionImport); // 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM if (list.size() >= BATCH_COUNT) { saveData(); // 存储完成清理 list list.clear(); } } @Override public void doAfterAllAnalysed(AnalysisContext context) { // 这里也要保存数据,确保最后遗留的数据也存储到数据库 saveData(); LOGGER.info("所有数据解析完成!"); } private void saveData() { LOGGER.info("{}条数据,开始存储数据库!", list.size()); LOGGER.info("存储数据库成功!"); } }
2.controller层
@PostMapping("/import")
@ApiOperation(value = "导入BzhdSystemConstruction对象", notes = "导入")
public ApiResult importBzhdSystemConstruction(MultipartFile file) throws Exception {
return bzhdSystemConstructionServiceImpl.importBzhdSystemConstruction(file);
}
3.serviceiml层
public ApiResultimportBzhdSystemConstruction(MultipartFile file) { try{ //获取文件流 InputStream inputStream = file.getInputStream(); //easyexcel导入文件 EasyExcel.read(inputStream, BzhdSystemConstructionImport.class,new BzhdSystemConstructionImportListener(bzhdSystemConstructionMapper)).sheet().doRead(); return ApiResult.ok(true); }catch (IOException e){ e.printStackTrace(); return ApiResult.fail("数据异常无法导入文件!"); } }



