easyexcel导出字典值的映射转换

主要是通过指定converter来实现

 

 具体converter代码如下

/**
 * easyexcel关于导出的字典值转换
 */
public class ExcelDictConverter implements Converter<Integer> {

    private String[] dictCodIsYesNoArr ={"afterSalesStatus", ""};


    @Override
    public Class supportJavaTypeKey() {
        return Integer.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Integer convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return null;
    }

    @Override
    public CellData convertToExcelData(Integer dictKey, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        // 类里需要转换的字段
        Field field = excelContentProperty.getField();
        String fieldName = field.getName();
        String excelValue;
        // 字典值为yes_no的字段
        if (StringUtils.equalsAnyIgnoreCase(fieldName, dictCodIsYesNoArr)) {
            excelValue = DictCache.getValue(DictEnum.YES_NO, dictKey);
        }else {
            // 将字段名转换成下划线连接(也就是字典表里的code
            String dictCode = camelToUnderline(fieldName);
            // 当前字段对应的字典值
            excelValue = DictCache.getValue(dictCode, dictKey);
        }
        return new CellData(StringUtil.isBlank(excelValue) ? dictKey.toString() : excelValue);
    }

    /**
     *         驼峰转成下划线
     *
     * @param sourStr 需要转换的字符串,如:orderStatus
     * @return 转换后的字符串,如:order_status
     */
    public String camelToUnderline(String sourStr) {
        if (sourStr == null || "".equals(sourStr.trim())) {
            return "";
        }
        int len = sourStr.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = sourStr.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append('_');
            }
            sb.append(Character.toLowerCase(c));
        }
        return sb.toString();
    }

}

 

posted @ 2021-03-10 17:38  hy_wx  阅读(8864)  评论(0编辑  收藏  举报