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

Java EasyExcel动态修改注解

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

Java EasyExcel动态修改注解

EasyExcel动态修改注解 @ExcelProperty修改Excel表头
业务场景:Excel表头标题会根据某些条件去改变
:Excel标题为:2022年活动数据

实现:

动态修改注解工具类:
    public void modifyFiled(Class clazz, Consumer consumer, String fieldName) throws Exception {
		//获取需要修改的属性
        Field field = clazz.getDeclaredField(fieldName);
		//获取注解
        ExcelProperty annotation = field.getAnnotation(ExcelProperty.class);
		//生成代理类对象
        InvocationHandler invocationHandler = Proxy.getInvocationHandler(annotation);
        Field annotationValues = invocationHandler.getClass().getDeclaredField("memberValues");

        annotationValues.setAccessible(true);
        Map map = (Map) annotationValues.get(invocationHandler);
        consumer.accept(map);
    }
导出Excel实体类:
@Data
@ColumnWidth(16)
@HeadRowHeight(57)
public class FiveAchievementScoreExcel implements Serializable {

    private static final long serialVersionUID = 1L;

    @ExcelProperty(index = 0, value = {"{%s}", "系统编号"})
    private String id;

    @ColumnWidth(7)
    @ExcelProperty(index = 1, value = {"{%s}", "序号"})
    private Integer reportNo;

    @ColumnWidth(36)
    @ExcelProperty(index = 2, value = {"{%s}", "项目名称"})
    @ApiModelProperty(value = "成果名称")
    private String achievementName;

    @ExcelProperty(index = 3, value = {"{%s}", "推荐值"})
    private Integer recommendIndex;
}
业务实现
    public void reBuildExcelPropertyValue(Class clazz, String title) throws Exception {

        Field[] exportFields = clazz.getDeclaredFields();
        for (Field field : exportFields) {

            ExcelProperty annotation = field.getAnnotation(ExcelProperty.class);
            if (annotation != null) {

                String[] value = annotation.value();

                if (StringUtils.startsWith(value[0], "{") && StringUtils.endsWith(value[0], "}")) {

                    modifyFiled(FiveAchievementScoreExcel.class, map -> {
                        map.put("value",
                                new String[]{StringUtils.replaceEach(String.format(value[0], title),
                                        new String[]{"{", "}"},
                                        new String[]{"", ""}),
                                        value[1]});
                    }, field.getName());
                }
            }
        }
    }
代码调用
 excelUtil.reBuildExcelPropertyValue(FiveAchievementScoreExcel.class, activityName);
                                  有喜欢的可以关注一下公众号哦

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/946194.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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