Java导出Excel动态表头的示例详解

2025-02-08 04:50

本文主要是介绍Java导出Excel动态表头的示例详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《Java导出Excel动态表头的示例详解》这篇文章主要为大家详细介绍了Java导出Excel动态表头的相关知识,文中的示例代码简洁易懂,具有一定的借鉴价值,有需要的小伙伴可以了解下...

前言

本文只记录大致思路以及做法,代码不进行详细输出

场景:

模板导出

1.按照模板内容类型分组(分sheet):1.文本消息;2.文本卡片;3.富文本;4.图文

2.每个类型的动态参数不同,即为每个sheet的表头不同

一、效果展示

Java导出Excel动态表头的示例详解

Java导出Excel动态表头的示例详解

二、代码实现

1.固定头实体类

@Data
@ApiModel
@ExcelIgnoreUnannotated
// @HeadRowHeight(value = 50)
// @ContentRowHeight(value = 50)
@ColumnWidth(value = 20)
public class MsgModuleInfoDTO {
 
    @ApiModelProperty(value = "模板id")
    private Long id;
 
    @ApiModelProperty(value = "模板ids")
    private List<Long> ids;
 
    @ApiModelProperty(value = "模板编码")
    @ExcelProperty(value = "模板编码")
    private String code;
 
    @ApiModelProperty(value = "模板名称")
    @ExcelProperty(value = "模板名称")
    private String name;
 
    @ApiModelProperty(value = "模板关联的渠道内容类型Code")
    private String contentTypeCode;
 
    @ApiModelProperty(value = "模板关联的渠道内容类型Value")
    @ExcelProperty(value = "内容类型")
    private String contentTypeValue;
 
    @ApiModelProperty(value = "业务场景")
    @ExcelProperty(value = "业务场景")
    private String condition;
 
 
    @ApiModelProperty(value = "所属应用id")
    private Integer appId;
 
    @ApiModelProperty(value = "所属应用名称")
    @ExcelProperty(value =China编程 "所属应用")
    private String appName;
 
    @ApiModelProperty(value = "是否启用(1:启用 ;0:不启用)")
    @ExcelProperty(value = "是否启用")
    private Integer isEnable;
 
 
    @ApiModelProperty(value = "app_消息跳转url")
    private String appUrl;
 
    @ApiModelProperty(value = "pc_消息跳转url")
    private String pcUrl;
 
    @ApiModelProperty(value = "模板标题")
    @ExcelProperty(value = "模板标题")
    private String title;
 
    @ApiModelProperty(value = "模板内容")
    @ExcelProperty(value = "模板内容")
    private String content;
 
    @ApiModelProperty(value = "富文本模板内容")
    @ExcelProperty(value = "富文本模板内容")
    private String richContent;
 
    private MessageTemplateDynamicProperties dynamicProperties;
 
    @ApiModelProperty(value = "修改时间")
    private LocalDateTime lastUpdateTime;
 
    @ApiModelProperty(value = "修改者用户ID")
    private Long lastUpdateUser;
 
    @ApiModelProperty(value = "修改者用户名称")
    private String lastUpdateUserName;
 
    @ApiModelProperty(value = "是否系统预设(1:是;0:不是)")
    @ExcelProperty(value = "是否系统预设", converter = MsgSystemConverter.class)
    private Integer isSystemType;
 
    @ApiModelProperty(value = "模板类型编码")
    private String msgFormCode;
 
    @ApiModelProperty(value = "模板类型名称")
    @ExcelProperty(value = "模板类型")
    private String msgFormName;
 
}

2.动态头实现

@Getter
@RequiredArgsConstructor(staticName = "of")
public class CodeAndValue {
    private final String code;
    private final String name;
    private final Object value;
}
/**
    渠道动态配置属性数据提供接口 
*/
public interface DynamicPropertiesGenerator {
    /**
     * 获取动态配置字段信息
     *
     * @return List<DynamicProperties>
     */
    @ApiModelProperty(hidden = true)
    @jsonIgnore
    List<CodeAndValue> getDynamicPropertiesList();
}
 
@ApiModel("模板动态字段配置数据")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "contentType")
@JsonSubTypes(value = {
        @JsonSubTypes.Type(value = MessageRichTextConfigurationDynamicProperties.class, name = "richTextMessage"),
        @JsonSubTypes.Type(value = MessageTextConfigurationDynamicProperties.class, name = "textMessage"),
        @JsonSubTypes.Type(value = MessageCardConfigurationDynamicProperties.class, name = "textCardMessage"),
        @JsonSubTypes.Type(value = MessagePictureConfigurationDynamicProperties.class, name = "pictureMessage")
})
public interface MessageTemplateDynamicProperties extends DynamicPropertiesGenerator {
}

MessageRichTextConfigurationDynamicProperties 富文本动态参数

@Getter
public class MessageRichTextConfigurationDynamicProperties implements MessageTemplateDynamicProperties {
    private final List<CodeAndValue> dynamicPropertiesList;
    @JsonIgnore
    private final MessageRichConfiguration messageCardConfiguration;
 
    @JsonCreator
    public MessageRichTextConfigurationDynamicProperties(@JsonProperty String messagePlatformRedirectUri,
                                                         @JsonProperty Boolean messagePlatformRedirectWithAgileUserInfo,
                                                         @JsonProperty String agileAppRedirectUri,
                                                         @JsonProperty String agileMainRedirectUri) {
        this.messageCardConfiguration = new MessageRichConfiguration(messagePlatformRedirectUri, messagePlatformRedirectWithAgileUserInfo, agileAppRedirectUri, agileMainRedirectUri);
        this.dynamicPropertiesList = DynamicValueUtil.configurationToDynamicProperties(messageCardConfiguration, Mapper.values());
    }
 
    public String getMessagePlatformRedirectUri() {
        return messageCardConfiguration.getMessagePlatformRedirectUri();
    }
 
    public Boolean getMessagePlatformRedirectWithAgileUserInfo() {
        return messageCardConfiguration.getMessagePlatformRedirectWithAgileUserInfo();
    }
 
    public String getAgileAppRedirectUri() {
        return messageCardConfiguration.getAgileAppRedirectUri();
    }
 
    public String getAgileMainRedirectUri() {
        return messageCardConfiguration.getAgileMainRedirectUri();
    }
 
 
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class MessageRichConfiguration {
        @ExcelProperty(value = "第三方平台富文本消息链接跳转地址")
        private String messagePlatformRedirectUri;
        @ExcelProperty(value = "第三方平台富文本消息链接跳转是否携带agile用户信息")
        private Boolean messagePlatformRedirectWithAgileUserInfo;
        @ExcelProperty(value = "Agile H5跳转地址")
        private String agileAppRedirectUri;
        @ExcelProperty(value = "AgiChina编程le PC跳转地址")
        private String agileMainRedirectUri;
    }
 
    @Getter
    @RequiredArgsConstructor
    enum Mapper implements DynamicValueMapper {
        MESSAGE_PLATFORM_REDIRECT_URI(LambdaUtil.getFieldName(MessageRichConfiguration::getMessagePlatformRedirectUri), "第三方平台富文本消息链接跳转地址"),
 
        MESSAGE_PLATFORM_REDIRECT_WITH_AGILE_USERINFO(LambdaUtil.getFieldName(MessageRichConfiguration::getMessagePlatformRedirectWithAgileUserInfo), "第三方平台富文本消息链接跳转是否携带agile用户信息"),
 
        AGILE_APP_REDIRECT_URI(LambdaUtil.getFieldName(MessageRichConfiguration::getAgileAppRedirectUri), "Agile H5跳转地址"),
 
        AGILE_MAIN_REDIRECT_URI(LambdaUtil.getFieldName(MessageRichConfiguration::getAgileMainRedirectUri), "Agile PC跳转地址"),
        ;
        private final String code;
        private final String name;
    }
}

MessageCardConfigurationDynamicProperties 文本卡片动态参数

@Getter
@SuppressWarnings("unused")
public class MessageCardConfigurationDynamicProperties implements MessageTemplateDynamicProperties {
    private final List<CodeAndValue> dynamicPropertiesList;
    @JsonIgnore
    private final MessageCardConfiguration messageCardConfiguration;
 
    @JsonCreator
    public MessageCardConfigurationDynamicProperties(@JsonProperty Boolean enableOauth2Link,
                                                     @JsonProperty String btnTxt,
                                                     @JsonProperty String messagePlatformRedirectUri,
                                                     @JsonProperty Boolean messagePlatformRedirectWithAgileUserInfo,
                                                     @JsonProperty String agileAppRedirectUri,
                                                     @JsonProperty String agileMainRedirectUri) {
        this.messageCardConfiguration = new MessageCardConfiguration(enableOauth2Link, btnTxt, messagePlatformRedirectUri, messagePlatformRedirectWithAgileUserInfo,
                agileAppRedirectUri, agileMainRedirectUri);
        this.dynamicPropertiesList = DynamicValueUtil.configurationToDynamicProperties(messageCardConfiguration, Mapper.values());
    }
 
    public Boolean getEnableOauth2Link() {
        return messageCardConfiguration.getEnableOauth2Link();
    }
 
    public String getBtnTxt() {
        return messageCardConfiguration.getBtnTxt();
    }
 
    public String getMessagePlatformRedirectUri() {
        return messageCardConfiguration.getMessagePlatformRedirectUri();
    }
 
    public Boolean getMessagePlatformRedirectWithAgileUserInfo() {
        return messageCardConfiguration.getMessagePlatformRedirectWithAgileUserInfo();
    }
 
    public String getAgileAppRedirectUri() {
        return messageCardConfiguration.getAgileAppRedirectUri();
    }
 
    public String getAgileMainRedirectUri() {
        return messageCardConfiguration.getAgileMainRedirectUri();
    }
 
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class MessageCardConfiguration {
        @ExcelProperty(value = "是否开启跳转链接")
        private Boolean enableOauth2Link;
        @ExcelProperty(value = "卡片消息跳转描述")
        private String btnTxt;
        @ExcelProperty(value = "平台跳转链接")
        private String messagePlatformRedirectUri;
        @ExcelProperty(value = "是否携带Agile用户信息")
        private Boolean messagePlatformRedirectWithAgileUserInfo;
        @ExcelProperty(value = "Agile H5跳转地址")
        private String agileAppRedirectUri;
        @ExcelProperty(value = "Agile PC跳转地址")
        private String agileMainRedirectUri;
    }
 
    @Getter
    @RequiredArgsConstructor
    enum Mapper implements DynamicValueMapper {
        ENABLE_OAUTH2_LINK(LambdaUtil.getFieldName(MessageCardConfiguration::getEnableOauth2Link), "跳转链接开启Oauth2授权"),
        BTN_TXT(LambdaUtil.getFieldName(MessageCardConfiguration::getBtnTxt), "卡片消息跳转描述"),
        MESSAGE_PLATFORM_REDIRECT_URI(LambdaUtil.getFieldName(MessageCardConfiguration::getMessagePlatformRedirectUri), "平台跳转链接"),
        MESSAGE_PLATFORM_REDIRECT_WITH_AGILE_USERINFO(LambdaUtil.getFieldName(MessageCardConfiguration::getMessagePlatformRedirectWithAgileUserInfo), "是否携带Agile用户信息"),
        AGILE_APP_REDIRECT_URI(LambdaUtil.getFieldName(MessageCardConfiguration::getAgileAppRedirectUri), "Agile H5 跳转路由"),
        AGILE_MAIN_REDIRECT_URI(LambdaUtil.getFieldName(MessageCardConfiguration::getAgileMainRedirectUri), "Agile PC 跳转路由"),
        ;
        private final String code;
        private final String name;
    }
}

3.导出动态头

/**
     * 按照模板内容类型分组(分sheet):1.文本消息;2.文本卡片;3.富文本;4.图文
  China编程   *
     * @param queryDto 查询条件
     * @param response 响应
     * @author zhumq
     * @date 2025/01/22 14:30:17
     */
    @Override
    @SneakyThrows
    public void exportExcel(QueryMsgModuleInfoDTO queryDto, HttpServletResponse response) {
 
        log.info("【模板导出】导出模板数据,传入参数[queryDto = {}]", queryDto);
 
        // 获取模板数据
        Page<MsgModulejavascriptInfoEntity> page = convertPageBean(new Paging(1, -1));
        List<MsgModuleInfoDTO> moduleList = msgModuleInfoMapper.selectPageInfo(queryDto, page);
 
        if (CollUtil.isEmpty(moduleList)) {
            log.info("【模板导出】查询不到可导出的模板,传入参数[queryDto = {}]", JsonUtil.toJson(queryDto));
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().println(JSONUtil.toJsonStr(ApiResult.failMessage("没有数据可以导出")));
            return;
        }
 
        // 设置响应
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel");
        String fileName = URLEncoder.encode("消息模板_" + System.currentTimeMillis(), "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
 
        ServletOutputStream outputStream = null;
        ExcelWriter excelWriter = null;
 
        try {
            outputStream = response.getOutputStream();
            excelWriter = EasyExcel.write(outputStream).build();
 
            // 按内容类型分组
            Map<String, List<MsgModuleInfoDTO>> contentMap = moduleList.stream()
                    .collect(Collectors.groupingBy(MsgModuleInfoDTO::getContentTypeCode));
 
            for (Map.Entry<String, List<MsgModuleInfoDTO>> entry : contentMap.entrySet()) {
                String contentType = entry.getKey();
                String sheetName = MsgEnum.ContentType.getLabelByKey(contentType);
 
                List<MsgModuleInfoDTO> items = entry.getValue();
 
                // 动态生成表头
                Map<String, Field> headMap = this.generateHeader(items);
                List<List<String>> head = headMap.keySet().stream()
                        .map(Collections::singletonList)
                        .collect(Collectors.toList());
 
                // 提取数据行
                List<List<Object>> dataList = this.obtainExportData(items, headMap);
                // 写入数据到不同的 sheet 使用动态生成的表头
                WriteSheet writeSheet = EasyExcel.writerSheet(sheetName)
                        .head(head)
                        .registerWriteHandler(new CustomColumnWidthStyleStrategy())
                        .build();
                excelWriter.write(dataList, writeSheet);
 
            }
 
            // 刷新输出流
            outputStream.flush();
        } catch (IOException e) {
            log.error("导出模板数据失败", e);
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().println(JSONUtil.toJsonStr(ApiResult.failMessage("下载文件失败")));
        } finally {
            // 关闭 ExcelWriter
            if (excelWriter != null) {
                excelWriter.finish();
            }
            // 关闭输出流
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error("关闭输出流失败", e);
                }
            }
        }
    }
 
    /**
     * 提取数据行
     *
     * @param items
     * @param headMap
     * @return {@link List }<{@link List }<{@link Object }>>
     * @author zhumq
     * @date 2025/01/22 14:59:11
     */
    private List<List<Object>> obtainExportData(List<MsgModuleInfoDTO> items, Map<String, Field> headMap) {
        List<List<Object>> dataList = new ArrayList<>();
        for (MsgModuleInfoDTO item : items) {
            List<Object> dataListRow = new ArrayList<>();
            // 填充固定字段
            for (Map.Entry<String, Field> entryField : headMap.entrySet()) {
                String fieldName = entryField.getKey();
                Field field = entryField.getValue();
                if (field != null) {
                    // 固定字段通过反射获取
                    try {
                        field.setAccessible(true);
                        Object value = field.get(item);
                        dataListRow.add(this.convertValue(value));
                    } catch (Exception e) {
                        log.error("反射获取字段值失败: {}", fieldName, e);
                        dataListRow.add("");
                    }
                } else {
                    // 动态字段通过getDynamicProperties获取
                    Object value = Optional.http://www.chinasem.cnofNullable(item.getDynamicProperties())
                            .map(MessageTemplateDynamicProperties::getDynamicPropertiesList)
                            .orElse(Collections.emptyList())
                            .stream()
                            .filter(cv -> cv.getName().equals(fieldName))
                            .findFirst()
                            .map(CodeAndValue::getValue)
                            .orElse("");
                    dataListRow.add(this.convertValue(value));
                }
            }
            dataList.add(dataListRow);
        }
        return dataList;
    }
 
    /**
     * 生成Excel表头结构
     *
     * @param items 模板数据
     * @return {@link Map }<{@link String }, {@link Field }>
     * @author zhumq
     * @date 2025/01/22 14:30:06
     */
    private Map<String, Field> generateHeader(List<MsgModuleInfoDTO> items) {
 
        // 1. 固定字段(通过反射获取DTO的@ExcelProperty)
        Map<String, Field> headerMap = new LinkedHashMap<>(this.getExcelHeader(MsgModuleInfoDTO.class));
 
        // 2. 动态字段(直接从dynamicPropertiesList提取code)
        if (CollUtil.isNotEmpty(items)) {
            MsgModuleInfoDTO firstItem = items.get(0);
            MessageTemplateDynamicProperties dynamicProperties = firstItem.getDynamicProperties();
            if (dynamicProperties != null && CollUtil.isNotEmpty(dynamicProperties.getDynamicPropertiesList())) {
                // 去重处理code,避免重复表头
                dynamicProperties.getDynamicPropertiesList().stream()
                        .map(CodeAndValue::getName)
                        .distinct()
                        .forEach(name -> headerMap.putIfAbsent(name, null));
            }
        }
        return headerMap;
    }
 
    /**
     * 工具方法:获取类中带有@ExcelProperty注解的字段
     *
     * @param clazz 类
     * @return {@link Map }<{@link String }, {@link Field }>
     * @author zhumq
     * @date 2025/01/22 14:29:55
     */
    private Map<String, Field> getExcelHeader(Class<?> clazz) {
        Map<String, Field> fieldMap = new LinkedHashMap<>();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(ExcelProperty.class)) {
                ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
                // 获取注解中的字段名称
                fieldMap.put(excelProperty.value()[0], field);
            }
        }
        return fieldMap;
    }
 
    /**
     * 转换字段值为字符串
     *
     * @param value
     * @return {@link Object }
     * @author zhumq
     * @date 2025/01/22 14:50:16
     */
    private Object convertValue(Object value) {
        if (value instanceof Boolean) {
            return (Boolean) value ? "是" : "否";
        } else if (value instanceof Integer) {
            return (Integer) value == 1 ? "是" : "否";
        } else if (value == null) {
            return "";
        }
        return value;
    }

到此这篇关于Java导出Excel动态表头的示例详解的文章就介绍到这了,更多相关Java导出Excel动态表头内容请搜索编程China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持China编程(www.chinasem.cn)!

这篇关于Java导出Excel动态表头的示例详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1153343

相关文章

一文全面详解Python变量作用域

《一文全面详解Python变量作用域》变量作用域是Python中非常重要的概念,它决定了在哪里可以访问变量,下面我将用通俗易懂的方式,结合代码示例和图表,带你全面了解Python变量作用域,需要的朋友... 目录一、什么是变量作用域?二、python的四种作用域作用域查找顺序图示三、各作用域详解1. 局部作

MySQL JSON 查询中的对象与数组技巧及查询示例

《MySQLJSON查询中的对象与数组技巧及查询示例》MySQL中JSON对象和JSON数组查询的详细介绍及带有WHERE条件的查询示例,本文给大家介绍的非常详细,mysqljson查询示例相关知... 目录jsON 对象查询1. JSON_CONTAINS2. JSON_EXTRACT3. JSON_TA

Java中实现线程的创建和启动的方法

《Java中实现线程的创建和启动的方法》在Java中,实现线程的创建和启动是两个不同但紧密相关的概念,理解为什么要启动线程(调用start()方法)而非直接调用run()方法,是掌握多线程编程的关键,... 目录1. 线程的生命周期2. start() vs run() 的本质区别3. 为什么必须通过 st

关于跨域无效的问题及解决(java后端方案)

《关于跨域无效的问题及解决(java后端方案)》:本文主要介绍关于跨域无效的问题及解决(java后端方案),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录通用后端跨域方法1、@CrossOrigin 注解2、springboot2.0 实现WebMvcConfig

Java SWT库详解与安装指南(最新推荐)

《JavaSWT库详解与安装指南(最新推荐)》:本文主要介绍JavaSWT库详解与安装指南,在本章中,我们介绍了如何下载、安装SWTJAR包,并详述了在Eclipse以及命令行环境中配置Java... 目录1. Java SWT类库概述2. SWT与AWT和Swing的区别2.1 历史背景与设计理念2.1.

使用SpringBoot整合Sharding Sphere实现数据脱敏的示例

《使用SpringBoot整合ShardingSphere实现数据脱敏的示例》ApacheShardingSphere数据脱敏模块,通过SQL拦截与改写实现敏感信息加密存储,解决手动处理繁琐及系统改... 目录痛点一:痛点二:脱敏配置Quick Start——Spring 显示配置:1.引入依赖2.创建脱敏

C++作用域和标识符查找规则详解

《C++作用域和标识符查找规则详解》在C++中,作用域(Scope)和标识符查找(IdentifierLookup)是理解代码行为的重要概念,本文将详细介绍这些规则,并通过实例来说明它们的工作原理,需... 目录作用域标识符查找规则1. 普通查找(Ordinary Lookup)2. 限定查找(Qualif

SpringBoot 中 CommandLineRunner的作用示例详解

《SpringBoot中CommandLineRunner的作用示例详解》SpringBoot提供的一种简单的实现方案就是添加一个model并实现CommandLineRunner接口,实现功能的... 目录1、CommandLineRunnerSpringBoot中CommandLineRunner的作用

Java死锁问题解决方案及示例详解

《Java死锁问题解决方案及示例详解》死锁是指两个或多个线程因争夺资源而相互等待,导致所有线程都无法继续执行的一种状态,本文给大家详细介绍了Java死锁问题解决方案详解及实践样例,需要的朋友可以参考下... 目录1、简述死锁的四个必要条件:2、死锁示例代码3、如何检测死锁?3.1 使用 jstack3.2

详解Linux中常见环境变量的特点与设置

《详解Linux中常见环境变量的特点与设置》环境变量是操作系统和用户设置的一些动态键值对,为运行的程序提供配置信息,理解环境变量对于系统管理、软件开发都很重要,下面小编就为大家详细介绍一下吧... 目录前言一、环境变量的概念二、常见的环境变量三、环境变量特点及其相关指令3.1 环境变量的全局性3.2、环境变