controller层
@ApiOperation(value = "批量导入", notes = "导入模板,然后入库")
@RequestMapping(value = "/list-import", produces = "text/plain;charset=UTF-8", method = RequestMethod.POST)
public RestResponse getExcels(@RequestParam("file") MultipartFile file) {
try {
String originalFileName = file.getOriginalFilename();
String filename = originalFileName.substring(originalFileName.lastIndexOf("."));
if (!".xls".equals(filename) && !".xlsx".equals(filename)) {
return RestResponse.fail("请使用xlsx或xls文件进行导入");
}
RestResponse verifyResult = indicService.verifyList(file);
return verifyResult;
} catch (Exception var5) {
log.error("模板导入失败", var5);
return RestResponse.fail("模板数据不完整,请在模板内补全数据再进行导入");
}
}
service层:
@Override
public RestResponse verifyList(MultipartFile file) throws Exception {
String originalName = file.getOriginalFilename();
String name = file.getName();
logger.info("=导入==开始==originalName:" + originalName);
logger.info("=导入==开始==name:" + name);
ExcelReader excelReader = ExcelUtil.getReader(file.getInputStream());
Set<String> listTemp = new HashSet<String>();
List<List<Object>> impDataList = excelReader.read(0);
String message = "";
String lineString = "";
boolean flag = false;
if (CollUtil.isNotEmpty(impDataList)) {
String titleStr = ((List) impDataList.get(0)).get(0).toString();
logger.info("=导入====titleStr:" + titleStr);
if (!titleStr.contains("编码")) {
throw new BusinessException("请使用正确的指标导入模板导入数据");
} else {
List<List<Object>> impData = excelReader.read(1);
if (ObjectUtil.isNotNull(impData)) {
List<dao1> indicList = new ArrayList<>();
boolean rowBoolean = true;
for (List<Object> row : impData) {
dao1 entity = new dao1();
if (StrUtil.isNotEmpty(Convert.toStr(row.get(0)))) {
entity.setIndicKey(Convert.toStr(row.get(0)));//指标编码
}else{
rowBoolean = false;
break;
}
if (StrUtil.isNotEmpty(Convert.toStr(row.get(1)))) {
entity.setIndicName(Convert.toStr(row.get(1)));//指标名称
}else{
message = "指标名称为空!请修改后重试";
rowBoolean = false;
break;
}
//指标描述 ---- 可以为空
entity.setIndicDescription(Convert.toStr(row.get(2)));
indicList.add(entity);
}
if(rowBoolean == true && CollectionUtils.isNotEmpty(indicList)){
flag = this.addIndicList(indicList);//批量导入
}else{
return RestResponse.fail(message);
}
if (flag) {
message = "成功导入" + (impDataList.size() - 1) + "条数据";
if (impDataList.size() - 1 == 0) {
return RestResponse.fail("模板数据为空,请在模板内添加数据再进行导入");
}
} else {
return RestResponse.fail("请使用正确的指标导入模板导入数据");
}
} else {
return RestResponse.fail("请使用正确的指标导入模板导入数据");
}
}
}
return RestResponse.successMsg(message);
}