廉洁沈阳网站,深圳宝安区通告,wang域名建的网站,微信小程序开发者模式目录 前言一、情景介绍二、问题分析三、代码实现方式一#xff1a;head 设置方式二#xff1a;模板导出方式三#xff1a;自定义工具类 前言
Java-easyExcel入门教程#xff1a;https://blog.csdn.net/xhmico/article/details/134714025
之前有介绍过如何使用 easyExcelhead 设置方式二模板导出方式三自定义工具类 前言
Java-easyExcel入门教程https://blog.csdn.net/xhmico/article/details/134714025
之前有介绍过如何使用 easyExcel以及写了两个入门的 demo 这两个 demo 能应付在开发中大多数的导入和导出需求不过有时候面对一些复杂的表格就会有点不够用该篇讲述的是如何实现复杂表头编写 一、情景介绍
在实际的开发过程中可能会遇到需要导出一些带有复杂表头的表格比如以下案例 该表头占了两行其中 橙色 部分的信息是需要动态生成的 二、问题分析
关于如何实现类似于上述复杂表头有多种方式均可实现首先这个表头是一个复杂表头其次还有动态的部分
查看官方文档对应复杂表头的实现
官方文档复杂头写入 从中可以看出多行表头就是由 多个纵向 的列表组成并且表头 相同的部分会自动合并居中对齐
再查阅官方文档关于如何实现动态头的写入
官方文档动态头、实时生成头写入 官方给了一个 head() 方法允许我们在代码中自定义表头 public T head(ListListString head) {this.parameter().setHead(head);return this.self();}三、代码实现 方式一head 设置
可以将上述表头看作是以下 6 个集合组成的表头然后使用 head() 方法去设置 代码示例 /*** 复杂表头编写方式一*/Testpublic void complexHeadDemo01() {// 输出文件路径String outFilePath D:\\excel-files\\demo01.xlsx;// 表格数据ListObject data new ArrayList();EasyExcel.write(outFilePath)// 动态头.head(head()).sheet()// 表格数据.doWrite(data);}private ListListString head() {ListListString list new ArrayListListString();ListString head0 new ArrayListString();head0.add(部门);head0.add(用户名称);ListString head1 new ArrayListString();head1.add(运营部);head1.add(性别);ListString head2 new ArrayListString();head2.add(运营部);head2.add(年龄);ListString head3 new ArrayListString();head3.add(时间);head3.add(出生日期);ListString head4 new ArrayListString();head4.add(2024-04-09);head4.add(学历);ListString head5 new ArrayListString();head5.add(2024-04-09);head5.add(电话号码);list.add(head0);list.add(head1);list.add(head2);list.add(head3);list.add(head4);list.add(head5);return list;}结果展示 可以看到是能够实现这种表头的不过需要自己定义表头的样式 方式二模板导出
可以使用模板导出的方式设置一个模板文件例如 实体类 DeptUserExcelEntity.java
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;Data
Builder
AllArgsConstructor
NoArgsConstructor
public class DeptUserExcelEntity {ApiModelProperty(value 用户名称)private String realName;ApiModelProperty(value 性别)private String gender;ApiModelProperty(value 年龄)private Integer age;ApiModelProperty(value 出生日期)private String birthdate;ApiModelProperty(value 学历)private String education;ApiModelProperty(value 电话号码)private String telephone;
}代码示例 /*** 复杂表头编写方式二*/Testpublic void complexHeadDemo02() {// 模板文件路径String templateFilePath D:\\excel-files\\template.xlsx;// 输出文件路径String outFilePath D:\\excel-files\\demo02.xlsx;// 创建 ExcelWriter 实例ExcelWriter writer EasyExcel// 写入到.write(outFilePath)// 指定模板.withTemplate(templateFilePath).build();WriteSheet sheet EasyExcel.writerSheet().build();MapString, String replaceMap new HashMap();replaceMap.put(deptName, 运营部);replaceMap.put(currentDate, 2024-04-09);// 执行填充普通占位符操作writer.fill(replaceMap, sheet);// 获取员工信息ListDeptUserExcelEntity data new ArrayList();FillConfig fillConfig FillConfig.builder()// 开启填充换行.forceNewRow(true).build();// 执行填充列表操作writer.fill(data, fillConfig, sheet);// 结束writer.finish();}结果展示 可以看到效果是比较好的也不用担心表格样式的问题
关于如何使用 easyexcel 实现按模板导出可参考easyExcel - 按模板导出 有较为详细的说明 方式三自定义工具类
根据官方实现复杂表头的写法自定义输出对象为
DeptUserExcelEntity.java
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.*;
import com.alibaba.excel.enums.poi.BorderStyleEnum;
import com.alibaba.excel.enums.poi.FillPatternTypeEnum;
import com.alibaba.excel.enums.poi.HorizontalAlignmentEnum;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;Data
Builder
AllArgsConstructor
NoArgsConstructor
// 头背景设置
HeadStyle(fillPatternType FillPatternTypeEnum.SOLID_FOREGROUND, horizontalAlignment HorizontalAlignmentEnum.CENTER, borderLeft BorderStyleEnum.THIN, borderTop BorderStyleEnum.THIN, borderRight BorderStyleEnum.THIN, borderBottom BorderStyleEnum.THIN)
//标题高度
HeadRowHeight(40)
//内容高度
ContentRowHeight(30)
//内容居中,左、上、右、下的边框显示
ContentStyle(horizontalAlignment HorizontalAlignmentEnum.CENTER, borderLeft BorderStyleEnum.THIN, borderTop BorderStyleEnum.THIN, borderRight BorderStyleEnum.THIN, borderBottom BorderStyleEnum.THIN)
public class DeptUserExcelEntity {ApiModelProperty(value 用户名称)ExcelProperty({部门,用户名称})ColumnWidth(15)private String realName;ApiModelProperty(value 性别)ExcelProperty({deptName,性别})ColumnWidth(15)private String gender;ApiModelProperty(value 年龄)ExcelProperty({deptName,年龄})ColumnWidth(15)private Integer age;ApiModelProperty(value 出生日期)ExcelProperty({时间,出生日期})ColumnWidth(15)private String birthdate;ApiModelProperty(value 学历)ExcelProperty({currentDate,学历})ColumnWidth(20)private String education;ApiModelProperty(value 电话号码)ExcelProperty({currentDate,电话号码})ColumnWidth(20)private String telephone;
}如果依照之前的导出案例代码如下 Testpublic void complexHeadDemo03_test() {// 输出文件路径String outFilePath D:\\excel-files\\demo03.xlsx;ListDeptUserExcelEntity excelEntities new ArrayList();EasyExcel.write(outFilePath, DeptUserExcelEntity.class).sheet().doWrite(excelEntities);}最后得到的表格也是根据输出对象定义而来的 所以如果能让表格在写入的时候输出对象 DeptUserExcelEntity 中 ExcelProperty 里面的 deptName 和 currentDate 替换成想要的不就行了所以我就自定义一个工具类在需要的时候改变注解的属性值就行了
工具类
AnnotationUtils.java
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;/*** 注解工具类*/
public class AnnotationUtils {/*** 变更注解的属性值再处理业务处理完业务之后恢复类的属性** param clazz 注解所在的实体类* param tClass 注解类* param attrName 要修改的注解属性名* param attrTypeEnum 要修改的注解属性的类型* param valueMap 要设置的属性值*/public static A extends Annotation void changeAnnotationValueToDealProcess(Class? clazz,ClassA tClass,String attrName,AttrTypeEnum attrTypeEnum,MapString, String valueMap,DealProcess dealProcess) {try {MapString, Object fieldAnnotationValueMap new HashMap();Field[] fields clazz.getDeclaredFields();for (Field field : fields) {A annotation field.getAnnotation(tClass);if (annotation null) continue;Object value setAnnotationValue(annotation, attrName, attrTypeEnum, valueMap);String fieldName field.getName();fieldAnnotationValueMap.put(fieldName, value);}// 处理业务逻辑dealProcess.deal();// 恢复for (Field field : fields) {A annotation field.getAnnotation(tClass);String fieldName field.getName();if (annotation null) continue;Object value fieldAnnotationValueMap.get(fieldName);InvocationHandler handler Proxy.getInvocationHandler(annotation);Field memberValuesField handler.getClass().getDeclaredField(memberValues);memberValuesField.setAccessible(true);SuppressWarnings(all)MapString, Object memberValues (Map) memberValuesField.get(handler);memberValues.put(attrName, value);}} catch (Exception e) {e.printStackTrace();}}/*** 设置注解中的字段值** param annotation 要修改的注解实例* param attrName 要修改的注解属性名* param attrTypeEnum 要修改的注解属性的类型* param valueMap 替换属性集的map*/SuppressWarnings(all)private static Object setAnnotationValue(Annotation annotation, String attrName,AttrTypeEnum attrTypeEnum, MapString, String valueMap) throws NoSuchFieldException, IllegalAccessException {InvocationHandler handler Proxy.getInvocationHandler(annotation);Field field handler.getClass().getDeclaredField(memberValues);field.setAccessible(true);Map memberValues (Map) field.get(handler);Object value memberValues.get(attrName);switch (attrTypeEnum) {case STRING: {String oldValue (String) value;String newValue valueMap.get(oldValue);if (StringUtils.isNotBlank(newValue)) {memberValues.put(attrName, newValue);}}break;case STRING_ARR: {String[] oldValue (String[]) value;String[] newValue new String[oldValue.length];for (int i 0; i oldValue.length; i) {String replace valueMap.get(oldValue[i]);newValue[i] replace ! null ? replace : oldValue[i];}memberValues.put(attrName, newValue);}break;}return value;}public enum AttrTypeEnum {STRING,STRING_ARR}public interface DealProcess {void deal() throws Exception;}}代码示例 /*** 复杂表头编写方式三*/Testpublic synchronized void complexHeadDemo03() {// 输出文件路径String outFilePath D:\\excel-files\\demo03.xlsx;// 替换注解中的属性值为HashMapString, String replaceMap new HashMap();replaceMap.put(deptName, 运营部);replaceMap.put(currentDate, 2024-04-09);/** 这里简单的说明一下* attrName: 对应的是 ExcelProperty 中的 value 属性* attrTypeEnum: 对应的是 ExcelProperty 中的 value 属性 的类型*/AnnotationUtils.changeAnnotationValueToDealProcess(DeptUserExcelEntity.class, ExcelProperty.class, value, AnnotationUtils.AttrTypeEnum.STRING_ARR, replaceMap, new AnnotationUtils.DealProcess() {Overridepublic void deal() {ListDeptUserExcelEntity excelEntities new ArrayList();EasyExcel.write(outFilePath, DeptUserExcelEntity.class).sheet().doWrite(excelEntities);}});}结果 这里要注意的是因为调用该方法时回去修改对应的 class 对象所以这里最好加锁
这种方式不仅可以处理 easyexcel 的注解动态表头问题也可以处理传统的 poi 的注解动态表头目前也是我用得比较多的一种方式