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;

}

相关推荐
进阶小白猿6 分钟前
Java技术八股学习Day26
java·开发语言·学习
余瑜鱼鱼鱼8 分钟前
synchronized总结
java·开发语言
小宇的天下9 分钟前
Calibre :SVRF rule file example
java·开发语言·数据库
码农水水10 分钟前
大疆Java面试被问:使用Async-profiler进行CPU热点分析和火焰图解读
java·开发语言·jvm·数据结构·后端·面试·职场和发展
i建模16 分钟前
在Windows系统上通过SSH访问远程AWS主机
windows·ssh·aws
我真的是大笨蛋17 分钟前
MVCC解析
java·数据库·spring boot·sql·mysql·设计模式·设计规范
hcnaisd218 分钟前
使用Python进行PDF文件的处理与操作
jvm·数据库·python
不会代码的小测试18 分钟前
UI自动化-针对验证码登录的系统,通过首次手动登录存储cookie的方式后续访问免登录方法
开发语言·python·selenium
秃头续命码农人19 分钟前
谈谈对Spring、Spring MVC、SpringBoot、SpringCloud,Mybatis框架的理解
java·spring boot·spring·mvc·maven·mybatis