EasyExcel 字典转换 BaseDictConverter

BaseDictConverter

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.cdhld.esp.api.entity.system.Dictionary;
import com.cdhld.esp.api.exception.ExcelErrorException;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * Excel 字典导入时输入的是汉字,数据库存储的是字典值
 *
 * @author zph
 * @date 2024/4/25 19:00
 */
@Slf4j
@Setter
public abstract class BaseDictConverter implements Converter<Long> {

    //字典集合
    List<Dictionary> dicts = null;

    //匹配不到时 是否报错,还是置为null
    boolean throwError = true;

    @Override
    public Class<Long> supportJavaTypeKey() {
        return Long.class;
    }

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

    @Override
    public Long convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        //没有值,直接报错
        if (StrUtil.isNotBlank(cellData.getStringValue())) {
            if (CollUtil.isNotEmpty(dicts)) {
                for (Dictionary dictionary : dicts) {
                    if (dictionary.getRemark().equals(cellData.getStringValue())) {
                        return dictionary.getValue();
                    }
                }
            }
            if (throwError) {
                log.error("excel导入,字典转换失败:dicts:{} value:{}", dicts, cellData.getStringValue());
                throw new ExcelDataConvertException(cellData.getRowIndex(), cellData.getColumnIndex(), cellData, contentProperty, StrUtil.format("字典值'{}'不存在", cellData.getStringValue()));
            }
        }
        return null;
    }

    @Override
    public CellData<String> convertToExcelData(Long value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        if (CollUtil.isNotEmpty(dicts)) {
            for (Dictionary dictionary : dicts) {
                if (dictionary.getValue().equals(value)) {
                    return new CellData<>(dictionary.getRemark());
                }
            }
        }
        if (throwError) {
            log.error("excel导出,字典转换失败:dicts:{} value:{}", dicts, value);
            throw new ExcelErrorException("字典转换失败");
        }
        return new CellData<>("");
    }

}

字典对象

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.time.LocalDateTime;

/**
 *
 * @author zph
 * @date 2024/4/25
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("t_dictionary")
@ApiModel(value = "Dictionary对象", description = "字典表")
public class Dictionary implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId
    private Long id;

    @ApiModelProperty(value = "字典项名称")
    private String name;

    @ApiModelProperty(value = "字典项值")
    private Long value;

    @ApiModelProperty(value = "备注")
    private String remark;

    @ApiModelProperty(value = "父级id")
    private Long parentId;

    @ApiModelProperty(value = "逻辑删除")
    private Integer deleted;

    @ApiModelProperty(value = "created_time")
    private LocalDateTime createdTime;

    @ApiModelProperty(value = "updated_time")
    private LocalDateTime updatedTime;

}

导入\导出对象

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.cdhld.esp.api.converter.BaseDictConverter;
import com.cdhld.esp.api.entity.system.Dictionary;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;
import java.util.List;

/**
 *
 * @author zph
 * @date 2024/4/25 13:54
 */
@Data
public class BusDataExcelDTO implements Serializable {

    private static final long serialVersionUID = 1L;

    @ExcelProperty(index = 0)
    @ApiModelProperty("序号")
    private Integer no;

    @ExcelProperty(index = 1, converter = TypeCoverter.class)
    @ApiModelProperty("类型")
    private Long type;


    public static class TypeCoverter extends BaseDictConverter {

        //字典集合
        public static List<Dictionary> dicts = null;

        //匹配不到时 是否报错,还是置为null
        boolean throwError = false;

        @Override
        public Long convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
            super.setDicts(dicts);
            super.setThrowError(throwError);
            return super.convertToJavaData(cellData, contentProperty, globalConfiguration);
        }

        @Override
        public CellData<String> convertToExcelData(Long value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
            super.setDicts(dicts);
            super.setThrowError(throwError);
            return super.convertToExcelData(value, contentProperty, globalConfiguration);
        }
    }

}

使用

    public void exportProject(HttpServletResponse response) {
        List<BusDataExcelDTO> dataList = CollUtil.newArrayList();
        //设置类型字典值
        BusDataExcelDTO.TypeCoverter.dicts = dictionarySrv.getList(100L);
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("数据列表", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), BusDataExcelDTO.class).sheet("数据列表").doWrite(dataList);
        } catch (Exception e) {
            log.error("导出异常:", e);
            throw new RuntimeException("导出异常");
        }
    }
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用 EasyExcel 进行读取 Excel 文件时,如果需要将 Excel 表格中的枚举值转换成对应的 Java 枚举类型,可以使用 EasyExcel 提供的 `com.alibaba.excel.annotation.format.*` 注解来实现。 具体步骤如下: 1. 定义 Java 枚举类型: ```java public enum GenderEnum { MALE("男"), FEMALE("女"); private String value; GenderEnum(String value) { this.value = value; } public String getValue() { return value; } } ``` 2. 在实体类中使用 `@ExcelProperty` 注解并指定 `format` 属性,将 Excel 中的列与实体类中的属性进行映射,并指定对应的转换器类: ```java public class User { @ExcelProperty(value = "性别", index = 2) @FormatEnum(EnumConverter.class) // 指定转换器 private GenderEnum gender; // 省略其他属性和方法 } ``` 3. 实现 `EnumConverter` 类,继承 `com.alibaba.excel.converters.string.StringConverter` 并重写 `convertToJavaData()` 方法: ```java public class EnumConverter extends StringConverter { @Override public Class<?> supportJavaTypeKey() { return GenderEnum.class; } @Override public Object convertToJavaData(String value, ExcelContentProperty contentProperty) throws Exception { if (StringUtils.isEmpty(value)) { return null; } return GenderEnum.valueOf(value.toUpperCase()); } } ``` 在上述代码中,`supportJavaTypeKey()` 方法指定了需要转换Java 类型,`convertToJavaData()` 方法实现了将 Excel 中的字符串值转换成对应的枚举类型的逻辑。 完成上述步骤后,使用 EasyExcel 读取 Excel 文件时即可自动将枚举值转换成对应的 Java 枚举类型。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值