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;

}

相关推荐
低头不见3 分钟前
策略模式上下文管理
windows·python·策略模式
Xander W4 分钟前
基于K8s集群的PyTorch DDP 框架分布式训练测试(开发机版)
人工智能·pytorch·分布式·python·深度学习·kubernetes
亚林瓜子7 分钟前
SpringBoot中使用tess4j进行OCR(在macos上面开发)
java·spring boot·macos·ocr·lstm·tess4j
文火冰糖的硅基工坊15 分钟前
[人工智能-大模型-103]:模型层 - M个神经元组成的单层神经网络的本质
python·算法·机器学习
坚持就完事了17 分钟前
XPath语法及Python的lxml包学习
python
电脑小管家18 分钟前
笔记本蓝牙怎么开启 完整教程
windows·驱动开发·计算机外设·电脑·音频
孤独的追光者19 分钟前
使用Qt Designer开发上位机
开发语言·python·qt
狂团商城小师妹24 分钟前
JAVA国际版同城打车源码同城服务线下结账系统源码适配PAD支持Android+IOS+H5
android·java·ios·小程序·交友
杨超越luckly24 分钟前
HTML应用指南:利用POST请求获取全国爱回收门店位置信息
大数据·前端·python·信息可视化·html
m0_7369270427 分钟前
Java面试场景题及答案总结(2025版持续更新)
java·开发语言·后端·职场和发展