EasyExcel动态修改注解 @ExcelProperty修改Excel表头
业务场景:Excel表头标题会根据某些条件去改变
🌰:Excel标题为:2022年活动数据
实现:
动态修改注解工具类:
public void modifyFiled(Class clazz, Consumer<Map> consumer, String fieldName) throws Exception {
//获取需要修改的属性
Field field = clazz.getDeclaredField(fieldName);
//获取注解
ExcelProperty annotation = field.getAnnotation(ExcelProperty.class);
//生成代理类对象
InvocationHandler invocationHandler = Proxy.getInvocationHandler(annotation);
Field annotationValues = invocationHandler.getClass().getDeclaredField("memberValues");
annotationValues.setAccessible(true);
Map map = (Map) annotationValues.get(invocationHandler);
consumer.accept(map);
}
导出Excel实体类:
@Data
@ColumnWidth(16)
@HeadRowHeight(57)
public class FiveAchievementScoreExcel implements Serializable {
private static final long serialVersionUID = 1L;
@ExcelProperty(index = 0, value = {"{%s}", "系统编号"})
private String id;
@ColumnWidth(7)
@ExcelProperty(index = 1, value = {"{%s}", "序号"})
private Integer reportNo;
@ColumnWidth(36)
@ExcelProperty(index = 2, value = {"{%s}", "项目名称"})
@ApiModelProperty(value = "成果名称")
private String achievementName;
@ExcelProperty(index = 3, value = {"{%s}", "推荐值"})
private Integer recommendIndex;
}
业务实现
public void reBuildExcelPropertyValue(Class<?> clazz, String title) throws Exception {
Field[] exportFields = clazz.getDeclaredFields();
for (Field field : exportFields) {
ExcelProperty annotation = field.getAnnotation(ExcelProperty.class);
if (annotation != null) {
String[] value = annotation.value();
value[0] = "{%s}";
if (StringUtils.startsWith(value[0], "{") && StringUtils.endsWith(value[0], "}")) {
modifyFiled(clazz, map -> {
map.put("value",
new String[]{StringUtils.replaceEach(String.format(value[0], title),
new String[]{"{", "}"},
new String[]{"", ""}),
value[1]});
}, field.getName());
}
}
}
}
代码调用
excelUtil.reBuildExcelPropertyValue(FiveAchievementScoreExcel.class, activityName);
有喜欢的可以关注一下公众号哦