1,在pom.xml 中引入
<dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.2.0-beta1</version> </dependency>
2.创建excel 表格中的对象
@Data public class DeviceUpdateData { @ExcelProperty(value = "设备识别码(必填;识别码+前后缀)") private String deviceCode; @ExcelProperty(value = "设备ID") private String deviceId; }
3,上传的监听
package com.jtl.device.common.util; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.event.AnalysisEventListener; import com.alibaba.fastjson.JSONObject; import com.jtl.common.util.RedisUtils; import com.jtl.common.util.SecurityUtils; import com.jtl.device.common.constant.Constants2; import com.jtl.device.service.biz.IJtlDeviceExcelBizService; import com.jtl.device.service.vo.DeviceUpdateData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class UploadDataListener extends AnalysisEventListener<DeviceUpdateData> { private static final Logger LOGGER = LoggerFactory.getLogger(UploadDataListener.class); private RedisUtils redisUtils; //这个是redis数据库 private static Integer dbIndex = 3; /** * 每隔2条存储数据库,实际使用中可以3000条,然后清理list ,方便内存回收 */ private static final int BATCH_COUNT = 2; List<DeviceUpdateData> list = new ArrayList<>(); /** * 假设这个是一个DAO,当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。 这个service 是我自己业务中需要的 */ private IJtlDeviceExcelBizService deviceExcelBizService; List<Object> defeated = new ArrayList<>(); List<Object> succeed = new ArrayList<>(); List<Object> register = new ArrayList<>(); List<Object> notRegister = new ArrayList<>(); /** * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来 注意这个地方 你在这个方法中用到几个service 在构造方法中要把你所引用到的service诶引进来 * * @param deviceExcelBizService */ public UploadDataListener(IJtlDeviceExcelBizService deviceExcelBizService,RedisUtils redisUtils) { this.deviceExcelBizService = deviceExcelBizService; this.redisUtils = redisUtils; } /** * 这个每一条数据解析都会来调用 初始化 进来就要调用到的方法 * * @param data one row value. Is is same as {@link AnalysisContext#readRowHolder()} * @param context */ @Override public void invoke(DeviceUpdateData data, AnalysisContext context) { LOGGER.info("解析到一条数据:{}", JSONObject.toJSON(data)); list.add(data); // 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM if (list.size() >= BATCH_COUNT) { // 这个是我自己的业务方法 存入数据库的方法 学习的可以忽略 List<Map<String, List>> maps = deviceExcelBizService.saveData(list); // 这个方法是我存完数据库 然后吧存到数据库 或者注册到电信平台注册成功的id 搜集起来 方便等一下存到redis中 addData(maps); // 存储完成清理 list list.clear(); } } /** * 所有数据解析完成了 都会来调用 * * @param context */ @Override public void doAfterAllAnalysed(AnalysisContext context) { // 这里也要保存数据,确保最后遗留的数据也存储到数据库 自己的业务方法 List<Map<String, List>> maps = deviceExcelBizService.saveData(list); addData(maps); LOGGER.info("所有数据解析完成!"); List<Map<String, List>> mapList = new ArrayList<>(); Map<String,List> map = new HashMap<>(); map.put("succeed",succeed); map.put("defeated",defeated); map.put("registerSuccess",register); map.put("registerFall",notRegister); mapList.add(map); saveRedis(mapList); } private void addData(List<Map<String, List>> maps){ if(maps!=null){ maps.stream().forEach(map->{ List<Object> list1 = map.get("succeed"); if(list1.size()>0){ list1.stream().forEach(key->{ succeed.add(key); }); } List<Object> list2 = map.get("defeated"); if(list2.size()>0){ list2.stream().forEach(key->{ defeated.add(key); }); } List<Object> list3 = map.get("registerSuccess"); if(list3.size()>0){ list3.stream().forEach(key->{ register.add(key); }); } List<Object> list4 = map.get("registerFall"); if(list4.size()>0){ list4.stream().forEach(key->{ notRegister.add(key); }); } }); } } /** * 加上存储数据库 */ private void saveRedis (List<Map<String, List>> maps){ Long id = SecurityUtils.getUser().getId(); redisUtils.hset(Constants2.Batch_Import+"_" + id,String.valueOf(id),maps); System.out.print("添加到redis"); } }
4,看controller怎么写的
package com.jtl.device.controller; import com.alibaba.excel.EasyExcel; import com.jtl.common.result.BaseResult; import com.jtl.common.util.RedisUtils; import com.jtl.common.util.SecurityUtils; import com.jtl.device.common.constant.Constants2; import com.jtl.device.common.util.UploadDataListener; import com.jtl.device.service.biz.IJtlDeviceExcelBizService; import com.jtl.device.service.biz.impl.IJtlDeviceExcelBizServiceImpl; import com.jtl.device.service.vo.DeviceUpdateData; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.log4j.Log4j; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.List; import java.util.Map; /** * @ProjectName: jtl-spring-cloud-all * @Package: com.jtl.device.controller * @ClassName: JtlDeviceExcelController * @Author: Administrator * @Description: ${description} * @Date: 2020/3/19 0019 10:59 * @Version: 1.0 */ @RestController @RequestMapping("/inner/jtlDeviceExcel") @Api(description = "批量操作controller") @Slf4j public class JtlDeviceExcelController { @Autowired private IJtlDeviceExcelBizService deviceExcelBizService; @Autowired private RedisUtils redisUtils; @PostMapping("/upload") @ResponseBody public BaseResult upload(MultipartFile file) throws IOException { BaseResult baseResult = new BaseResult(); EasyExcel.read(file.getInputStream(), DeviceUpdateData.class, new UploadDataListener(deviceExcelBizService,redisUtils)).sheet(0).headRowNumber(1).doRead(); baseResult.setSuccess(true); return baseResult; } @GetMapping("/getData") @ResponseBody @ApiOperation(value = "获取数据") public BaseResult getData(){ BaseResult baseResult = new BaseResult(); Long id = SecurityUtils.getUser().getId(); // Long id = 1000000000000009L; List<Map<String, List>> list = (List<Map<String, List>>) redisUtils.hget(Constants2.Batch_Import + "_" + id, String.valueOf(id)); if(list.size()>0){ baseResult.setValue(list); } baseResult.setSuccess(true); return baseResult; } }
来源:oschina
链接:https://my.oschina.net/liudandan/blog/3206680