我想要的Excel效果
在这里插入图片描述
说明:
1.创建两个自定义注解:@ExcelMerge(表示主对象内的单个属性,后续会根据子集合的大小合并下面的单元格),@ExcelNestedList(表示嵌套的子集合)
2.NestedDataConverter.java 会把查询到的数据转换为一行一行的,相当于主表 left join 子表 ON 主.id=子.主id的形式
SmartMergeStrategy.java 在使用EasyExcel时使用的策略类,会计算每组数据需要合并的row层数
3. public void t3()执行的Main方法.

package xxx.annotation;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;/*** 标记主实体中需要合并的字段*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelMerge {// 可以添加其他属性,如合并策略等
}
package xxx.annotation;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;/*** 标记包含子列表的字段*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelNestedList {Class<?> value(); // 指定子元素的类型
}
package xxx.common;import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;import org.springframework.stereotype.Component;import com.alibaba.excel.annotation.ExcelProperty;import xxx.annotation.ExcelNestedList;public class NestedDataConverter {public static List<List<Object>> convertToNestedListWithNesting(List<?> dataList) {List<List<Object>> result = new ArrayList<>();if (dataList.isEmpty()) {return result;}// Extract parameter names to maintain the orderClass<?> clazz = dataList.get(0).getClass();List<String> parameterNames = extractParameterNames(clazz);for (Object data : dataList) {List<Field> nestedFields = Arrays.stream(clazz.getDeclaredFields()).filter(f -> f.isAnnotationPresent(ExcelNestedList.class)).collect(Collectors.toList());if (nestedFields.isEmpty()) {// No nested fields, convert the object directlyresult.add(convertSingleToList(data, parameterNames));} else {Map<String, Object> fieldValues = new HashMap<>();populateFieldValues(data, fieldValues);for (Field nestedField : nestedFields) {try {nestedField.setAccessible(true);List<?> nestedList = (List<?>) nestedField.get(data);Class<?> nestedClass = nestedField.getAnnotation(ExcelNestedList.class).value();if (nestedList == null || nestedList.isEmpty()) {// Add a row with empty strings for nested fieldsList<Object> row = buildRowFromFieldValues(fieldValues, parameterNames, nestedClass, true);result.add(row);} else {for (Object nestedItem : nestedList) {Map<String, Object> nestedFieldValues = new HashMap<>(fieldValues);populateFieldValues(nestedItem, nestedFieldValues);List<Object> row = buildRowFromFieldValues(nestedFieldValues, parameterNames, nestedClass, false);result.add(row);}}} catch (IllegalAccessException e) {throw new RuntimeException("Failed to access nested data", e);}}}}return result;}private static void populateFieldValues(Object data, Map<String, Object> fieldValues) {for (Field field : data.getClass().getDeclaredFields()) {ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);if (excelProperty != null) {try {field.setAccessible(true);Object value = field.get(data);fieldValues.put(excelProperty.value()[0], value != null ? value : ""); // Replace null with empty string} catch (IllegalAccessException e) {fieldValues.put(excelProperty.value()[0], ""); // Add empty string if inaccessible}}}}private static List<Object> buildRowFromFieldValues(Map<String, Object> fieldValues, List<String> parameterNames, Class<?> nestedClass, boolean isEmptyNested) {List<Object> row = new ArrayList<>();for (String paramName : parameterNames) {if (fieldValues.containsKey(paramName)) {row.add(fieldValues.get(paramName));} else if (isEmptyNested && isNestedField(paramName, nestedClass)) {row.add(""); // Add empty string for empty nested fields}}return row;}private static boolean isNestedField(String paramName, Class<?> nestedClass) {return Arrays.stream(nestedClass.getDeclaredFields()).anyMatch(f -> f.isAnnotationPresent(ExcelProperty.class) && f.getAnnotation(ExcelProperty.class).value()[0].equals(paramName));}private static List<Object> convertSingleToList(Object data, List<String> parameterNames) {List<Object> row = new ArrayList<>();Map<String, Object> fieldValues = new HashMap<>();for (Field field : data.getClass().getDeclaredFields()) {ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);if (excelProperty != null) {try {field.setAccessible(true);fieldValues.put(excelProperty.value()[0], field.get(data));} catch (IllegalAccessException e) {fieldValues.put(excelProperty.value()[0], ""); // Add empty string if inaccessible}}}// Add values in the order of parameterNamesfor (String paramName : parameterNames) {row.add(fieldValues.getOrDefault(paramName, ""));}return row;}public static List<String> extractParameterNames(Class<?> clazz) {List<String> parameterNames = new ArrayList<>();for (Field field : clazz.getDeclaredFields()) {// Check if the field is annotated with @ExcelPropertyExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);// Check if the field is annotated with @ExcelNestedListExcelNestedList nestedList = field.getAnnotation(ExcelNestedList.class);if (excelProperty != null && nestedList == null) {parameterNames.add(excelProperty.value()[0]); // Add the parameter name}// Check if the field is annotated with @ExcelNestedList
//            ExcelNestedList nestedList = field.getAnnotation(ExcelNestedList.class);if (nestedList != null) {// Recursively extract parameter names from the nested classClass<?> nestedClass = nestedList.value();parameterNames.addAll(extractParameterNames(nestedClass));}}return parameterNames;}
}
package xxx.common;import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.merge.AbstractMergeStrategy;import xxx.annotation.ExcelMerge;public class SmartMergeStrategy extends AbstractMergeStrategy {private final List<?> dataList;private final Class<?> clazz;private final Map<Integer, List<int[]>> mergeInfo = new HashMap<>(); public SmartMergeStrategy(List<?> dataList, Class<?> clazz) {this.dataList = dataList;this.clazz = clazz;prepareMergeInfo();}private void prepareMergeInfo() {// 获取所有带有@ExcelMerge注释的字段List<Field> mergeFields = Arrays.stream(clazz.getDeclaredFields()).filter(field -> field.isAnnotationPresent(ExcelMerge.class)).collect(Collectors.toList());int currentRow = 1; // Start from row 1 (after the header)从第 1 行开始(标题之后)for (Object data : dataList) {try {// Get the `id` field value
//                Field idField = clazz.getDeclaredField("id");
//                idField.setAccessible(true);
//                Object idValue = idField.get(data);// 获取嵌套的 `forwards` 列表
//                Field nestedField = clazz.getDeclaredField("forwards");Field nestedField = Arrays.stream(clazz.getDeclaredFields()).filter(f -> List.class.isAssignableFrom(f.getType())).findFirst().orElseThrow(() -> new RuntimeException("未找到 List 类型字段"));nestedField.setAccessible(true);List<?> nestedList = (List<?>) nestedField.get(data);int nestedSize = (nestedList != null) ? nestedList.size() : 0;int startRow = currentRow;int endRow = (nestedSize > 0) ? (currentRow + nestedSize - 1) : currentRow;// 计算每个“@ExcelMerge”列的合并范围for (Field field : mergeFields) {int colIndex = getColumnIndex(field);if (colIndex >= 0 && startRow != endRow) {mergeInfo.computeIfAbsent(colIndex, k -> new ArrayList<>()).add(new int[]{startRow, endRow});}}// Update the current row pointer更新当前行指针currentRow = endRow + 1;} catch (IllegalAccessException e) {e.printStackTrace();}}}private int getColumnIndex(Field field) {ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);if (excelProperty != null) {String[] values = excelProperty.value();if (values.length > 0) {String columnName = values[0];List<Field> allFields = Arrays.stream(clazz.getDeclaredFields()).filter(f -> f.isAnnotationPresent(ExcelProperty.class)).collect(Collectors.toList());for (int i = 0; i < allFields.size(); i++) {Field currentField = allFields.get(i);ExcelProperty property = currentField.getAnnotation(ExcelProperty.class);if (property != null && property.value().length > 0 && property.value()[0].equals(columnName)) {return i;}}}}return -1;}@Overrideprotected void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) {int colIndex = cell.getColumnIndex();if (mergeInfo.containsKey(colIndex)) {List<int[]> ranges = mergeInfo.get(colIndex);for (int[] range : ranges) {int startRow = range[0];int endRow = range[1];if (cell.getRowIndex() == startRow) {CellRangeAddress region = new CellRangeAddress(startRow, endRow, colIndex, colIndex);sheet.addMergedRegion(region);}}}}}
package xxx.entity;import java.util.List;import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;import lombok.Data;
import xxx.annotation.ExcelMerge;
import xxx.annotation.ExcelNestedList;@Data
@TableName(value = "bkdb3.actions")
public class Action {@TableId(type = IdType.AUTO)@ExcelProperty("ID")@ExcelMergeprivate Long id;@ExcelProperty("Struts-Conf")@ExcelMergeprivate String strutsconfName;@ExcelIgnoreprivate String attribute;@ExcelIgnoreprivate String name;@ExcelIgnoreprivate String parameter;@ExcelProperty("Path")@ExcelMergeprivate String path;@ExcelProperty("ActionClassPath")@ExcelMergeprivate String type;// 非数据库字段,用于关联 forward 列表@TableField(exist = false)@ExcelProperty("forwards")@ExcelNestedList(Forward.class)private List<Forward> forwards;}
package xxx.entity;import com.alibaba.excel.annotation.ExcelProperty;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;import lombok.Data;@Data
@TableName(value = "bkdb3.forwards")
public class Forward {@TableId(type = IdType.AUTO)private Long id;private Long actionId; // 外键,关联 actions 表private String name;@ExcelProperty("forwardPath")private String path;}
/**把Action Forward输出为以下这种形式| Action ID | Action Name | Action Path | Forward Name | Forward Path || --------- | ----------- | ----------- | ------------ | ------------ || 1         | doLogin     | /login      | success      | /main.jsp    ||           |             |             | error        | /login.jsp   || 2         | doSearch    | /search     | next         | /result.jsp  |**/@Disabled@Testpublic void t3() {QueryWrapper<Action> wrapper = new QueryWrapper<>();wrapper.orderByAsc("id");List<Action> actions = actionMapper.selectList(wrapper);// 第二步:查询所有 forwards 一次性(推荐,一次查库,避免N+1)List<Long> actionIds = actions.stream().map(Action::getId).collect(Collectors.toList());if (!actionIds.isEmpty()) {List<Forward> allForwards = forwardMapper.selectList(new QueryWrapper<Forward>().in("action_id", actionIds));// 第三步:将 forwards 按照 actionId 分组Map<Long, List<Forward>> forwardMap = allForwards.stream().collect(Collectors.groupingBy(Forward::getActionId));// 第四步:将 forward 分别赋值到每个 Action 上for (Action action : actions) {List<Forward> childForwards = forwardMap.getOrDefault(action.getId(), new ArrayList<>());action.setForwards(childForwards);}}log.info("actions size={}",actions.size());List<List<Object>> lists = NestedDataConverter.convertToNestedListWithNesting(actions);// 4. 创建并注册合并策略SmartMergeStrategy mergeStrategy = new SmartMergeStrategy(actions, Action.class);// 获取所有可能的表头字段List<String> heads = NestedDataConverter.extractParameterNames(Action.class);// 5. 导出ExcelEasyExcel.write(analyzeProperties.getExcel1(),Action.class).registerWriteHandler(mergeStrategy) // 注册合并策略
//                .head(createHead(heads)) // 动态生成表头.sheet("Action").doWrite(lists);log.info("导出历史记录成功");}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/web/93192.shtml
繁体地址,请注明出处:http://hk.pswp.cn/web/93192.shtml
英文地址,请注明出处:http://en.pswp.cn/web/93192.shtml

如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

基于 C# WinForm 字体编辑器开发记录:从基础到进阶

目录 基础版本实现 进阶版本改进 字体设置窗体增强 主窗体改进 功能对比 项目在本文章的绑定资源中免费的&#xff0c;0积分就可以下载哦~ 在 Windows Forms 应用开发中&#xff0c;字体编辑功能是许多文本处理软件的基础功能。本文将分享一个简易字体编辑器的开发过程&a…

Linux基本使用和Java程序部署(含 JDK 与 MySQL)

文章目录Linux 背景知识Linux 基本使用Linux 常用的特殊符号和操作符Linux 常用命令文本处理与分析系统管理与操作用户与权限管理文件/目录操作与内容处理工具Linux系统防火墙Shell 脚本与实践搭建 Java 部署环境apt&#xff08;Debian/Ubuntu 系的包管理利器&#xff09;介绍安…

抗辐照CANFD通信芯片在高安全领域国产化替代的研究

摘要&#xff1a;随着现代科技的飞速发展&#xff0c;高安全领域如航空航天、卫星通信等对电子设备的可靠性与抗辐照性能提出了极高的要求。CANFD通信芯片作为数据传输的关键组件&#xff0c;其性能优劣直接关系到整个系统的稳定性与安全性。本文聚焦于抗辐照CANFD通信芯片在高…

Mybatis 源码解读-SqlSession 会话源码和Executor SQL操作执行器源码

作者源码阅读笔记主要采用金山云文档记录的&#xff0c;所有的交互图和代码阅读笔记都是记录在云文档里面&#xff0c;本平台的文档编辑实在不方便&#xff0c;会导致我梳理的交互图和文档失去原来的格式&#xff0c;所以整理在文档里面&#xff0c;供大家阅读交流. 【金山文档…

Java集合类综合练习题

代码 import java.util.*; class ScoreRecord {private String studentId;private String name;private String subject;private int score;public ScoreRecord(String studentId, String name, String subject, int score) {this.studentId studentId;this.name name;this.s…

秒懂边缘云|1分钟了解边缘安全加速 ESA

普通开发者如何搭建安全快速的在线业务才能性价比最高 &#xff1f;阿里云现已为开发者推出免费版边缘安全加速 ESA&#xff0c;1 个产品就能把 CDN 缓存 API 加速 DNS WAF DDoS 防护全部搞定&#xff0c;还支持边缘函数快速部署网站和 AI 应用&#xff0c;性价比拉满。 1…

数据结构:串、数组与广义表

&#x1f4cc;目录&#x1f524; 一&#xff0c;串的定义&#x1f330; 二&#xff0c;案例引入场景1&#xff1a;文本编辑器中的查找替换场景2&#xff1a;用户手机号验证&#x1f4da; 三&#xff0c;串的类型定义、存储结构及其运算&#xff08;一&#xff09;串的抽象类型定…

服务器路由相关配置Linux和Windows

服务器路由相关配置Linux和Windowscentos路由系统核心概念传统工具集(命令)iproute2 工具集&#xff08;推荐&#xff09;NetworkManager 工具路由配置文件体系高级路由功能策略路由多路径路由路由监控工具系统级路由配置启用IP转发路由守护进程路由问题诊断流程Windows 路由Wi…

Spring Boot启动事件详解:类型、监听与实战应用

1. Spring Boot启动事件概述1.1 什么是Spring Boot启动事件在Spring Boot的应用生命周期中&#xff0c;从main方法执行到应用完全就绪&#xff0c;期间会发生一系列事件&#xff08;Event&#xff09;。这些事件由Spring Boot框架在特定时间点触发&#xff0c;用于通知系统当前…

Python闭包详解:理解闭包与可变类型和不可变类型的关系

一、定义闭包&#xff08;Closure&#xff09; 指的是一个函数对象&#xff0c;即使其外部作用域的变量已经不存在了&#xff0c;仍然能访问这些变量。简单来说&#xff0c;闭包是由函数及其相关的环境变量组成的实体。def outer():x 10def inner():print(x)return innerf ou…

BotCash:GPT-5发布观察 工程优化的进步,还是技术突破的瓶颈?

BotCash&#xff1a;GPT-5发布观察 工程优化的进步&#xff0c;还是技术突破的瓶颈&#xff1f; 在GPT-4以多模态能力震撼业界的一年后&#xff0c;GPT-5的亮相显得有些“平静”。当人们期待着又一场颠覆性技术革命时&#xff0c;这场发布会更像是给大模型技术按下了“精细打磨…

AJAX学习(2)

目录 一.XMLHttpRequest 二.XMLHttpRequest——查询参数 三.案例——地区查询 四.XMLHttpRequest_数据提交 五.Promise 六.Promise三种状态 七.PromiseeeXHR获取省份列表&#xff08;案例&#xff09; 八.封装-简易axios-获取省份列表 九.封装-简易axios-获取地区列表 …

解决 pip 安装包时出现的 ReadTimeoutError 方法 1: 临时使用镜像源(单次安装)

解决 pip 安装包时出现的 ReadTimeoutError 当您在使用 pip 安装 Python 包时遇到 pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(hostfiles.pythonhosted.org, port443): Read timed out. 错误时&#xff0c;这通常是由于网络问题导致的连接超时。P…

Linux下使用Samba 客户端访问 Samba 服务器的配置(Ubuntu Debian)

在 Linux 系统中&#xff0c;Samba 提供了与 Windows 系统文件共享的便利方式。本文将详细介绍在 Ubuntu 和 Debian 系统下如何安装 Samba 客户端、访问共享资源&#xff0c;并实现远程目录挂载和开机自动挂载。 文章参考自&#xff08;感谢分享&#xff09;&#xff1a;https…

解决dedecms文章默认关键字太短的问题

在管理文章或软件的时候&#xff0c;大家在添加关键字和内容摘要的时候&#xff0c;是不是对这样的情况感到比较的郁闷&#xff0c;我的关键字设定的明明非常的好&#xff0c;可是添加或修改后&#xff0c;会被无缘无故的截去很多&#xff0c;想必大家也都非常的明白&#xff0…

K8s-kubernetes(二)资源限制-详细介绍

K8s如何合理规定对象资源使用 基本概念 Kubernetes中&#xff0c;占用资源的最小单元为单个PodKubernetes中&#xff0c;资源占用主要针对服务器的CPU、内存 为什么要做资源限制 对于Kubernetes集群而言&#xff0c;所有Pod都会占用K8s集群所在服务器的资源&#xff0c;如果不做…

量子神经网络:从NISQ困境到逻辑比特革命的破局之路

——解析2025千比特时代开发者的机遇与行动框架 引言:量子计算的“20比特魔咒”与千比特悖论 当开发者被建议“避免在>20量子比特电路训练”时,富士通却宣布2025年实现10,000物理比特系统。这一矛盾揭示了量子计算从NISQ时代向FTQC时代跃迁的核心逻辑:千比特突破非为直接…

react+vite-plugin-react-router-generator自动化生成路由

前言&#xff1a;react项目实际使用中有很多提升性能与功能的插件&#xff0c;今天来说一说vite里面提供的vite-plugin-react-router-generator&#xff0c;他主要提供了自动生成路由的功能&#xff0c;配合我们的loadable/component可以实现路由的懒加载与统一管理。1、实现效…

服务器查看 GPU 占用情况的方法

在 Linux 系统中查看 GPU 占用情况&#xff0c;主要取决于你的 GPU 类型&#xff08;NVIDIA/AMD&#xff09;&#xff0c;以下是常用方法&#xff1a; 一、NVIDIA GPU&#xff08;最常用&#xff0c;如 RTX 系列、Tesla 系列&#xff09; 使用 NVIDIA 官方工具 nvidia-smi&…

【Docker实战进阶】Docker 实战命令大全

Docker 实战命令大全 Docker 实战场景&#xff0c;以 Nginx 为核心示例&#xff0c;梳理容器生命周期、镜像管理、网络配置、数据持久化及 Compose 编排的核心命令与最佳实践。 一、容器生命周期管理 1. 基础生命周期命令 docker run - 创建并启动容器 核心功能&#xff1a;基于…