1.思路

思想1:校验当前接口对应的dto字段列是否与当前excel对应的表头是否匹配。
思想2:模板中创建一个隐藏sheet,每次导入的时候读取隐藏sheet的sheet名
思想3:读取当前sheet的sheet名并比对该接口应该对应的sheet名

2.代码实现

2.1 校验excel表头代码

	// 判断双方的导入列是否一致。true一致,false不一致
    private static boolean verifyExcelVersion(Class clazz, Sheet sheet) {
        List<Field> fields = getImportFields(clazz);
        List<String> classFieldList = fields.stream().map(item -> {
            return item.getAnnotation(MyExcel.class).name();
        }).collect(Collectors.toList());
        Row headRow = sheet.getRow(0);
        int headRowCount = headRow.getLastCellNum() - headRow.getFirstCellNum();
        // 读取excel表头
        List<String> headStringList = new ArrayList<>();
        for (int c = 0; c < headRowCount; c++) {
            Cell cell = headRow.getCell(c);
            String excelVal = cell.getStringCellValue();
            headStringList.add(excelVal);
        }
        // 使用md5进行信息摘要加密,比对两方信息是否一致
        String excelHeadMd5 = DigestUtil.md5Hex(headStringList.toString());
        String classFieldMd5 = DigestUtil.md5Hex(classFieldList.toString());
        return StrUtil.equals(excelHeadMd5, classFieldMd5);
    }

	// 获取dto对应的导入列
    private static List<Field> getImportFields(Class clazz) {
        List<Field> collect = Arrays.stream(clazz.getDeclaredFields()).filter(
                field -> field.isAnnotationPresent(MyExcel.class)
        ).sorted(
                Comparator.comparing(field -> field.getAnnotation(MyExcel.class).sort())
        ).collect(Collectors.toList());
        return collect;
    }

引用代码

        boolean verifyExcelVersion = verifyExcelVersion(clazz, sheet);
        if (!verifyExcelVersion) {
            throw new RunTimeException("导入模板异常");
        }
07-05 17:38