很多小伙伴都遇到使用EasyPoi 导出excel的时候,需要动态处理 replace 值的时候
直接贴代码
/**
* Excel工具
* @author xujuncheng
* @since 2022/5/23 9:19
* @param pojoClass
*/
public static void replaceHandel(Class<?> pojoClass){
Field[] fields = pojoClass.getDeclaredFields();
try {
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
// todo 这里可以加上指定字段做处理,也可以将需要的字段枚举或者是字段存到redis
Excel annotation = field.getAnnotation(Excel.class);
if (annotation != null && annotation.replace().length > 0) {
InvocationHandler invocationHandler = Proxy.getInvocationHandler(annotation);
Field memberValues = invocationHandler.getClass().getDeclaredField("memberValues");
memberValues.setAccessible(true);
Map map = (Map) memberValues.get(invocationHandler);
// replace 的值是字符串数组,自定义的时候记得数据格式
map.put("replace", new String[]{"枚举_1", "枚举_2","枚举_3","枚举_4","枚举_5"});
}
}
}catch (Exception e){
//可以抛自定义异常
e.printStackTrace();
}
}
调用
Class<GoodsStorageFlowExportDTO> aClass = GoodsStorageFlowExportDTO.class;
ExcelUtil.replaceHandel(aClass);
Workbook sheets = ExcelExportUtil.exportExcel(new ExportParams("111.xlsx", "111", ExcelType.XSSF), aClass, Arrays.asList(goodsStorageFlowExportDTO));