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;

}

相关推荐
石榴树下的七彩鱼11 分钟前
图片去水印 API 详解:从单图到批量自动化去水印(附 Python/JS/PHP 完整教程)
python·自动化·图片处理·图片去水印·石榴智能·api教程
薛定猫AI15 分钟前
Codex 与 Claude Code 全平台安装配置指南(Windows / macOS / Linux)
linux·windows·macos
Dicky-_-zhang1 小时前
系统容量规划与压测实战:从1万到100万QPS的科学扩容
java·jvm
console.log('npc')1 小时前
Windows 11 安装 WSL2 + Ubuntu + Docker + Codex + Sub2API 教学
windows·docker·powershell·ubantu·codex
Li emily6 小时前
解决了加密货币api多币种订阅时的数据乱序问题
人工智能·python·api·fastapi
Dicky-_-zhang6 小时前
消息队列Kafka/RocketMQ选型与高可用架构:从单体到100万TPS的演进
java·jvm
晨曦中的暮雨6 小时前
4.15腾讯 CSIG云服务产线 一面
java·开发语言
2301_781571427 小时前
Golang格式化输出占位符都有什么_Golang fmt占位符教程【通俗】
jvm·数据库·python
fake_ss1987 小时前
AI时代学习全栈项目开发的新范式
java·人工智能·学习·架构·个人开发·学习方法
asdzx677 小时前
使用 Python 为 PDF 添加页码 (详细教程)
python·pdf·页码