在工作中用到easyexcel,有一個上傳文件的功能,新模板比舊模板多了一列,因此產生當使用之前的舊模板時要拒掉,不能向下執行
程序中映射的實體類使用@ExcelProperty(value = "*二維碼編號", index = 0)注解,用於標識excel文件列的順序。
針對這個功能首先要獲取實體類的屬性上注解的內容,將內容與表頭內容進行匹配。
public static void main(String[] args) { //獲取單表頭的實體類順序 Class clazz = QrcodeUpdateParamsDto.class; //獲取類的所有屬性 Field[] declaredFields = clazz.getDeclaredFields(); List<FieldExcelProperty> fieldExcelPropertyList = new ArrayList<>(); FieldExcelProperty fieldExcelProperty = null; for (Field field: declaredFields) { System.out.println(field.toString()); ExcelProperty annotation = field.getAnnotation(ExcelProperty.class); if (annotation != null) { fieldExcelProperty = new FieldExcelProperty(); fieldExcelProperty.setIndex(annotation.index()); fieldExcelProperty.setValue(annotation.value()); fieldExcelPropertyList.add(fieldExcelProperty); fieldExcelProperty = null; } } if (!fieldExcelPropertyList.isEmpty()) { //利用拉姆達表達式,進行排序,將排序后的結果輸出為list } }
自定義內部類,用於保存屬性上注解的值
class FieldExcelProperty{ private int index; private String[] value; public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public String[] getValue() { return value; } public void setValue(String[] value) { this.value = value; } }
這樣將實體類轉換為表頭信息,再與讀取到的excel表頭做對比,headList為實體類對應的屬性集合。
@Override public void invokeHeadMap(Map headMap, AnalysisContext context) { if (context.readRowHolder().getRowIndex() == 0) { for (int i = 0; i < headList.length; i++) { try { if (null != headMap && null != headMap.get(i) && !headMap.get(i).equals(headList[i])) { throw new ExcelAnalysisException("上傳模板與系統模板不匹配,請使用平台模板上傳數據"); } } catch (Exception e) { throw new ExcelAnalysisException(e.getMessage()); } } } }
如果對比不一致,就會拒絕。