话不多说,直接上代码
模板读取解析
@Slf4j
@Data
public class ExcelAnalysisEventListener<T> extends AnalysisEventListener<T> {
private List<T> datas = new ArrayList<>();
@Override
public void invoke(T data, AnalysisContext analysisContext) {
datas.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
}
@Override
public void onException(Exception exception, AnalysisContext context) {
// 如果是某一个单元格的转换异常 能获取到具体行号
// 如果要获取头的信息 配合doAfterAllAnalysedHeadMap使用
if (exception instanceof ExcelDataConvertException) {
ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
log.error("第{}行,第{}列解析异常", excelDataConvertException.getRowIndex() + 1,
excelDataConvertException.getColumnIndex() + 1);
String msg = "第" + excelDataConvertException.getRowIndex() + 1 + "行,第" + excelDataConvertException.getColumnIndex() + 1 + "列解析异常";
throw BizException.createBizException(msg);
}
}
}
业务代码,根据自己业务调整
/**
* 定制课目录导入
*
* @return
*/
@Override
public Map<Boolean, List<? extends Object>> importData(MultipartFile file) throws IOException {
Map<Boolean, List<? extends Object>> map = new HashMap<>();
// 获取Excel文件中的数据
ExcelAnalysisEventListener<CourseWareCustomVO> listener = new ExcelAnalysisEventListener();
EasyExcelFactory.read(file.getInputStream(), CourseWareCustomVO.class, listener).sheet().doRead();
List<CourseWareCustomVO> datas = listener.getDatas();
//数据校验
List<String> errorMessageList = new ArrayList<>();
checkImportData(datas, errorMessageList);
if (CollectionUtils.isNotEmpty(errorMessageList)) {
map.put(false, errorMessageList);
} else {
map.put(true, datas);
}
return map;
}
private void checkImportData(List<CourseWareCustomVO> datas, List<String> errorMessageList) {
List<String> sortNoList = new ArrayList<>();
for (int i = 0; i < datas.size(); i++) {
CourseWareCustomVO courseWareCustomVO = datas.get(i);
//行数据为空
if (courseWareCustomVO == null) {
throw BizException.createBizException((i + 2) + "数据为空!");
}
if (StringUtils.isBlank(courseWareCustomVO.getSortNo())) {
errorMessageList.add("第[" + (i + 2) + "]行, 序号不能为空, 请确认后重新上传!");
} else {
if (sortNoList.contains(courseWareCustomVO.getSortNo())) {
errorMessageList.add("第[" + (i + 2) + "]行, 序号重复, 请确认后重新上传!");
}
}
sortNoList.add(courseWareCustomVO.getSortNo());
}
}