java使用@interface和反射来动态生成excel

1、对象类上搞注解

public class ReportExecuteDetailDto {

// 项目信息

private String regionCode; // 大区编号

@ExcelColumn(order = 0, title = "大区")

private String regionName; // 大区名称

@ExcelColumn(order = 14, title = "行申请金额", dataType = ExcelColumn.FieldType.Number)

private BigDecimal detailApplyAmount; // 行申请金额

}

2、创建注解类

package cn.com.ibm.portal.subject.annotation;

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.FIELD)

@Documented

public @interface ExcelColumn {

/**

* 标注该属性的顺序

* @return 该属性的顺序

*/

int order();

/**

* execl标题

* @return

*/

String title();

/**

* 日期数据的格式化格式

* @return

*/

String format() default "";

/**

* 单元格宽度

* @return

*/

int width() default 30;

/**

* 是否设置默认值:字符串默认为""

* Number:0.00

* Date: now

* Percent: 0.00%

*/

boolean hasDefault() default false;

/**

* 数据类型

* @return

*/

FieldType dataType() default FieldType.String;

public static enum FieldType {

/*

字符串

*/

String,

/*

数值

*/

Number,

/*

日期

*/

Date,

/*

百分比

*/

Percent;

}

}

3、获取属性

private static List<Field> getExcelColumnAnnotation(Class clazz) {

// 用来存放所有的属性域

List<Field> fieldList = Lists.newArrayList();

// 过滤带有注解的Field

for (Field f : clazz.getDeclaredFields()) {

if (f.getAnnotation(ExcelColumn.class) != null) {

fieldList.add(f);

}

}

// 这个比较排序的语法依赖于java 1.8

fieldList.sort(Comparator.comparingInt(

m -> m.getAnnotation(ExcelColumn.class).order()

));

return fieldList;

}

4、使用

private static List<PoiCellVo> genExecuteReportTitleData(ReportExecuteDto dto, int startRow, int startCol) {

List<PoiCellVo> result = Lists.newArrayList();

//添加固定标题

int fixStartRow = startRow;

int fixStartCol = startCol;

// 根据注解获取标题

List<Field> annotationList = getExcelColumnAnnotation(ReportExecuteDetailDto.class);

PoiCellVo fixVo = null;

ExcelColumn annotation = null;

for (Field field : annotationList) {

annotation = field.getAnnotation(ExcelColumn.class);

if (annotation == null) {

continue;

}

fixVo = new PoiCellVo(annotation.title(), fixStartRow, fixStartCol, 1, 1, headerColor, (short) annotation.width(), (short) 0);

result.add(fixVo);

fixStartCol++;

}

return result;

}

相关推荐
zhuhezhang几秒前
一个用python开发的文本对比工具
python·文本对比工具
智算菩萨1 分钟前
【Python图像处理】5 Pillow图像处理与格式转换
图像处理·python·pillow
开开心心就好2 分钟前
支持自定义名单的实用随机抽签工具
windows·计算机视觉·计算机外设·excel·散列表·启发式算法·csdn开发云
无限码力8 分钟前
华为OD技术面真题 - JAVA开发- spring框架 - 7
java·开发语言·华为od·华为od面试真题·华为odjava八股文·华为odjava开发题目·华为odjava开发高频题目
人工干智能10 分钟前
科普:%%matplotlib inline:魔法命令 (Cell Magic)
python·matplotlib
05大叔13 分钟前
优化器Adam,神经网络处理文本,CNN,RNN
开发语言·python·机器学习
Lyyaoo.14 分钟前
【JAVA基础面经】JAVA中的异常
java·开发语言
一定要AK28 分钟前
JVM 全体系深度解析笔记
java·jvm·笔记
coder阿龙29 分钟前
基于SpringAI+Qdrant+Ollama本地模型和向量数据库开发问答和RAG检索
java·数据库·spring boot·ai·数据库开发
Gofarlic_OMS29 分钟前
HyperWorks用户仿真行为分析与许可证资源分点配置
java·大数据·运维·服务器·人工智能