導出模板代碼,原理是combo屬性 傳遞一個數組 里面是label下拉數組。
@Overridepublic void downloadTemplate(HttpServletResponse response) {ExcelUtil<ThMachineryManageExcel> util = new ExcelUtil<>(ThMachineryManageExcel.class);List<SysDistrictExcel> districtExcelCache = DistrictUtils.getDistrictExcelCache();String[] array = districtExcelCache.stream().map(SysDistrictExcel::getName).toArray(String[]::new);util.combo("districtCode", array);util.importTemplateExcel(response, "數據模板");}
導入代碼映射邏輯 util.readConverterExp 映射數據,數據結構是String類型多個逗號隔開:label=value
@Overridepublic R<?> importData(MultipartFile file) throws IOException {ExcelUtil<ThMachineryManageExcel> util = new ExcelUtil<>(ThMachineryManageExcel.class);List<SysDistrictExcel> districtExcelCache = DistrictUtils.getDistrictExcelCache();Map<String, SysDistrictExcel> districtMap = districtExcelCache.stream().collect(Collectors.toMap(SysDistrictExcel::getCode, district -> district));String readConverterExp = districtExcelCache.stream().map(district -> district.getCode() + "=" + district.getName()).collect(Collectors.joining(","));// 映射數據label和value util.readConverterExp("districtCode", readConverterExp);List<ThMachineryManageExcel> excelList = util.importExcel(file.getInputStream());if (ObjectUtil.isEmpty(excelList)){throw new ServiceException("導入數據不能為空!");}List<ThMachineryManage> saveOrUpdateList = new ArrayList<>();int successNum = 0;int updateNum = 0;int errorNum = 0;StringBuilder successMsg = new StringBuilder();for (ThMachineryManageExcel data : excelList){try {ThMachineryManage topic = BeanUtil.copyProperties(data, ThMachineryManage.class);//校驗基本數據BeanValidators.validateWithException(validator,topic);ThMachineryManage oneData = getOne(new LambdaQueryWrapper<ThMachineryManage>().eq(ThMachineryManage::getBrand, data.getBrand()));//校驗通過 開始檢測數據是否重復if (ObjectUtil.isNotNull(oneData)){//說明是更新數據topic.setId(oneData.getId());updateNum++;}else {successNum++;}SysDistrictExcel sysDistrictExcel = districtMap.get(data.getDistrictCode());//業務邏輯 存儲行政區更多的數據topic.setCountyCode(sysDistrictExcel.getCountyCode());topic.setTownCode(sysDistrictExcel.getTownCode());topic.setVillageCode(sysDistrictExcel.getVillageCode());topic.setDistrictLevel("2");topic.setDistrictName(sysDistrictExcel.getName());saveOrUpdateList.add(topic);}catch (Exception e){errorNum++;int count = excelList.indexOf(data);String message = e.getMessage();successMsg.append("第").append(count+1).append("條數據導入失敗,原因:").append(message).append(";");break;}}// 數據全部正確時 進行批量插入/更新if (!saveOrUpdateList.isEmpty()&&errorNum==0){super.saveOrUpdateBatch(saveOrUpdateList);if (successNum>0){successMsg.append("成功導入").append(successNum).append("條數據");}if (updateNum>0){successMsg.append("成功更新").append(updateNum).append("條數據");}return R.ok(successMsg.toString());}else {return R.fail(successMsg.toString());}}