问题描述
我需要使用map 来表示一个对象
但是每个map里面的属性 是 可能不一样的 这就导致 最后生成excel的 时候 出现了 标题和值乱序的问题
这是因为默认选择第一行的属性来生成标题 其他的map 按照第一行的自动填充
HashMap testBean = new HashMap();
testBean.put("name","xxxx");
testBean.put("age","age");
// testBean.put("score","score");
testBean.put("isPass","isPass");
testBean.put("examDate","examDate");
// testBean.put("address","address");
testBean.put("ip",null);
HashMap testBean1 = new HashMap();
testBean1.put("isPass","isPass");
// testBean1.put("name",null);
testBean1.put("age","age");
testBean1.put("score","score");
// testBean1.put("examDate","examDate");
testBean1.put("address","address");
// testBean1.put("ip","ip");
List<HashMap> rows11 = CollUtil.newArrayList(testBean,testBean1);
//通过工具类创建writer
ExcelWriter writer = ExcelUtil.getWriter("D:\\tmp\\writeTest.xlsx");
//自定义标题别名
writer.addHeaderAlias("name", "姓名");
writer.addHeaderAlias("age", "年龄");
writer.addHeaderAlias("score", "分数");
writer.addHeaderAlias("isPass", "是否通过");
writer.addHeaderAlias("examDate", "考试时1间");
writer.addHeaderAlias("address", "地址");
writer.addHeaderAlias("ip", "ip地址");
// 默认的,未添加alias的属性也会写出,如果想只写出加了别名的字段,可以调用此方法排除之
writer.setOnlyAlias(true);
//一次性写出内容,强制输出标题
writer.write(rows11);
writer.close();
结果
解决办法
因为我们有一个方法 可以获取到 所有的标题
这样我们在每次map 填充之前 先对所有属性进行赋值为i空 然后 再取替换
HashMap<String, Object> data = new HashMap<>(32);
//填充所有属性 防止excel 生成 错位
tableTileList.forEach(e->{
data.put(e.getProp(),null);
});
for (Field field : reportCompose.getClass().getDeclaredFields()) {
if (field.getType().equals(List.class)) {
for (OrgExMngExceptionReportItems item : reportCompose.getReportItemsList()) {
data.put(item.getItemCode(), itemValueConverter(item.getItemValue()));
}
} else {
Object value = ReflectUtil.getFieldValue(reportCompose, field.getName());
if (ObjectUtil.isNotNull(value)) {
data.put(field.getName(), value);
}
}
}