工具类 package com.ruoyi.web.controller.tool; import com.ruoyi.biz.domain.ModelAttribute; import com.ruoyi.common.annotation.Excel; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.util.Map; public class JavasistUtils { public static Class configClass(Class c, Map<String, ModelAttribute> attributeMap) { Field[] fields = c.getDeclaredFields(); try { for (int i = 0; i < fields.length; i++) { Field f = fields[i]; String attributeName = f.getName(); if (attributeName.startsWith("param_")) { if (attributeMap.containsKey(attributeName)) { String attributeLable = attributeMap.get(attributeName).getAttributeLabel(); Excel excelAn = f.getAnnotation(Excel.class);//Excel是注解类型 if (excelAn == null) { continue; } InvocationHandler h = Proxy.getInvocationHandler(excelAn); Field hField = h.getClass().getDeclaredField("memberValues"); // 因为这个字段是 private 修饰,所以要打开权限 hField.setAccessible(true); // 获取 memberValues Map memberValues = (Map) hField.get(h); // 修改 value 属性值 这里修改的是@Excel(name = "姓名") //name是key memberValues.put("name", attributeLable); } } } } catch (Exception e) { e.printStackTrace(); } return c; } }
调用:
Model model = modelService.selectModelById(article.getModelId()); List<ModelAttribute> attributeList = model.getAttributeList(); Map<String, ModelAttribute> attributeMap = attributeList.stream() .collect(Collectors.toMap(ModelAttribute::getAttributeField, v -> v)); List<Article> list = articleService.selectExportArticleByIds(article.getIds()); ExcelUtil<Article> util = new ExcelUtil<Article>(JavasistUtils.configClass(Article.class, attributeMap)); util.exportExcel(response, list, "文章数据");