导出模板代码,原理是combo属性 传递一个数组 里面是label下拉数组。
@Override
public 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
@Override
public 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());
}
}