栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

easy-poi动态设置replace值

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

easy-poi动态设置replace值

背景

springBoot 使用easy-poi导出excel的时候对于使用字典的字段,需要使用replace将值和value按规定列出来,但既然使用了字典,那我们原则上就是希望直接用户自己修改字典值,之后所有功能依旧使用;若我们导出将所有值列出来则与初衷相违背,因此,我们可以使用切面动态修改replace值,上代码。

代码实现

1. 自定义注解

@documented
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelReplace {
    Class value() default Object.class;
}

2. 定义切面

@Aspect
@Component
public class ExcelReplaceAspect {
	
	// 字典注入,按需引用
    @Autowired
    private StackDictTypeService stackDictTypeService;

    // 切点
    @Pointcut("@annotation(io.ctc.utils.annotations.ExcelReplace)")
    public void excelReplacePointcut(){

    }

    // 执行之前的逻辑
    @Before("excelReplacePointcut()")
    public void around(JoinPoint point) throws NoSuchFieldException, IllegalAccessException {
        // 字典map
        Map> dictMap = stackDictTypeService.getAllList().stream().collect(Collectors.toMap(StackDictType::getDictType, StackDictType::getDataList));
        // 获取自定义注解配置的value---实体类
        MethodSignature signature = (MethodSignature) point.getSignature();
        ExcelReplace annotation = signature.getMethod().getAnnotation(ExcelReplace.class);
        // 获取对应实体
        Class exportClass = annotation.value();
        // 通过反射获取实体的所有字段
        Field[] declaredFields = exportClass.getDeclaredFields();
        for (Field field : declaredFields) {
            // 判断该字段是否带有@Excel注解
            Excel excel = field.getAnnotation(Excel.class);
            if(excel != null){
                // 获取excel注解的所有参数值
                InvocationHandler invocationHandler = Proxy.getInvocationHandler(excel);
                Field value = invocationHandler.getClass().getDeclaredField("memberValues");
                value.setAccessible(true);
                Map memberValues = (Map) value.get(invocationHandler);
                // 判断是否设置了有效的字典项
                if(StringUtils.isNotBlank(excel.dict()) && dictMap.get(excel.dict()) != null){
                    List list = dictMap.get(excel.dict()).stream().map(data -> data.getDictLabel() + "_" + data.getDictValue()).collect(Collectors.toList());
                    // 添加空
                    list.add("_null");
                    memberValues.put("replace", list.toArray(new String[0]));
                }
            }
        }
    }
}

3.实体使用

    
    @Excel(name = "所属域",dict = "dictDomain")
    private String dictDomain;

4. 导出方法

    @ExcelReplace(PhycomputersInfoExportDto.class)
    @PostMapping("export")
    public void export(@RequestBody Map params, HttpServletResponse response) {
    // 您的导出
	}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/315109.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号