动态匹配实体类的字段,并控制导出的excel内容
excel内容大同小异,现在主要是记录动态导出的列
public void xxxx(){
Map map = mapList();
String [] strings = {
"姓名","时间","号码"};
String getS = null;
// 获得需要匹配的实体字段
for(int i = 0; i < strings.length; i++){
if(map.get(strings[i]) != null){
if(!StringUtil.isNotEmpty(getS)){
getS = map.get(strings[i]).toString() ;
}else {
getS +="," + map.get(strings[i]).toString() ;
}
}
}
// 把实体字段改为数组
String[] result = getS.split(",");
// 数据添加
One one = new One();
one.setName("张三");
one.setDate(LocalDate.now());
one.setHospitalNo("111111");
Class clazz = one.getClass();
String[] contents = new String[result.length];
// 根据实体字段循环添加到行数组里面
for (int i = 0; result != null && i < result.length; i++) {
String filedName = toUpperCaseFirstOne(result[i]);
Object obj = null;
try {
Method method = clazz.getMethod(filedName);
method.setAccessible(true);
obj = method.invoke(one);
} catch (Exception e) {
}
String str = String.valueOf(obj);
if (str == null || str.equals("null"))
str = "";
contents[i] = str;
}
for(int i = 0; i < contents.length; i++){
// .....Excel的行数据
}
System.out.println(getS);
}
/**
* 方法把首字母大写 配合get
* @param origin
* @return
*/
private static String toUpperCaseFirstOne(String origin) {
StringBuffer sb = new StringBuffer(origin);
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
sb.insert(0, "get");
return sb.toString();
}
/**
* 实体类的中文与字段
*/
public Map mapList(){
Map map = new HashMap();
map.put("姓名","name");
map.put("时间","date");
map.put("号码","no");
map.put("年龄","ageGroup");
}