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

相关文章

Linux环境变量&&进程地址空间详解

《Linux环境变量&&进程地址空间详解》本文介绍了Linux环境变量、命令行参数、进程地址空间以及Linux内核进程调度队列的相关知识,环境变量是系统运行环境的参数,命令行参数用于传递给程序的参数,... 目录一、初步认识环境变量1.1常见的环境变量1.2环境变量的基本概念二、命令行参数2.1通过命令编程

Linux之进程状态&&进程优先级详解

《Linux之进程状态&&进程优先级详解》文章介绍了操作系统中进程的状态,包括运行状态、阻塞状态和挂起状态,并详细解释了Linux下进程的具体状态及其管理,此外,文章还讨论了进程的优先级、查看和修改进... 目录一、操作系统的进程状态1.1运行状态1.2阻塞状态1.3挂起二、linux下具体的状态三、进程的

10个Python Excel自动化脚本分享

《10个PythonExcel自动化脚本分享》在数据处理和分析的过程中,Excel文件是我们日常工作中常见的格式,本文将分享10个实用的Excel自动化脚本,希望可以帮助大家更轻松地掌握这些技能... 目录1. Excel单元格批量填充2. 设置行高与列宽3. 根据条件删除行4. 创建新的Excel工作表5

深入解析Spring TransactionTemplate 高级用法(示例代码)

《深入解析SpringTransactionTemplate高级用法(示例代码)》TransactionTemplate是Spring框架中一个强大的工具,它允许开发者以编程方式控制事务,通过... 目录1. TransactionTemplate 的核心概念2. 核心接口和类3. TransactionT

Java实现Elasticsearch查询当前索引全部数据的完整代码

《Java实现Elasticsearch查询当前索引全部数据的完整代码》:本文主要介绍如何在Java中实现查询Elasticsearch索引中指定条件下的全部数据,通过设置滚动查询参数(scrol... 目录需求背景通常情况Java 实现查询 Elasticsearch 全部数据写在最后需求背景通常情况下

Spring Boot 整合 ShedLock 处理定时任务重复执行的问题小结

《SpringBoot整合ShedLock处理定时任务重复执行的问题小结》ShedLock是解决分布式系统中定时任务重复执行问题的Java库,通过在数据库中加锁,确保只有一个节点在指定时间执行... 目录前言什么是 ShedLock?ShedLock 的工作原理:定时任务重复执行China编程的问题使用 Shed

一文详解Java Condition的await和signal等待通知机制

《一文详解JavaCondition的await和signal等待通知机制》这篇文章主要为大家详细介绍了JavaCondition的await和signal等待通知机制的相关知识,文中的示例代码讲... 目录1. Condition的核心方法2. 使用场景与优势3. 使用流程与规范基本模板生产者-消费者示例

开启mysql的binlog日志步骤详解

《开启mysql的binlog日志步骤详解》:本文主要介绍MySQL5.7版本中二进制日志(bin_log)的配置和使用,文中通过图文及代码介绍的非常详细,需要的朋友可以参考下... 目录1.查看是否开启bin_log2.数据库会把日志放进logs目录中3.查看log日志总结 mysql版本5.71.查看

deepseek本地部署使用步骤详解

《deepseek本地部署使用步骤详解》DeepSeek是一个开源的深度学习模型,支持自然语言处理和推荐系统,本地部署步骤包括克隆仓库、创建虚拟环境、安装依赖、配置模型和数据、启动服务、调试与优化以及... 目录环境要求部署步骤1. 克隆 DeepSeek 仓库2. 创建虚拟环境3. 安装依赖4. 配置模型

Sentinel 断路器在Spring Cloud使用详解

《Sentinel断路器在SpringCloud使用详解》Sentinel是阿里巴巴开源的一款微服务流量控制组件,主要以流量为切入点,从流量路由、流量控制、流量整形、熔断降级、系统自适应过载保护、... 目录Sentinel 介绍同类对比Hystrix:Sentinel:微服务雪崩问题问题原因问题解决方案请