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();
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM