问题描述

我需要使用map 来表示一个对象
但是每个map里面的属性 是 可能不一样的 这就导致 最后生成excel的 时候 出现了 标题和值乱序的问题

这是因为默认选择第一行的属性来生成标题 其他的map 按照第一行的自动填充

  1. HashMap testBean = new HashMap();
  2. testBean.put("name","xxxx");
  3. testBean.put("age","age");
  4. // testBean.put("score","score");
  5. testBean.put("isPass","isPass");
  6. testBean.put("examDate","examDate");
  7. // testBean.put("address","address");
  8. testBean.put("ip",null);
  9. HashMap testBean1 = new HashMap();
  10. testBean1.put("isPass","isPass");
  11. // testBean1.put("name",null);
  12. testBean1.put("age","age");
  13. testBean1.put("score","score");
  14. // testBean1.put("examDate","examDate");
  15. testBean1.put("address","address");
  16. // testBean1.put("ip","ip");
  17. List<HashMap> rows11 = CollUtil.newArrayList(testBean,testBean1);
  18. //通过工具类创建writer
  19. ExcelWriter writer = ExcelUtil.getWriter("D:\\tmp\\writeTest.xlsx");
  20. //自定义标题别名
  21. writer.addHeaderAlias("name", "姓名");
  22. writer.addHeaderAlias("age", "年龄");
  23. writer.addHeaderAlias("score", "分数");
  24. writer.addHeaderAlias("isPass", "是否通过");
  25. writer.addHeaderAlias("examDate", "考试时1间");
  26. writer.addHeaderAlias("address", "地址");
  27. writer.addHeaderAlias("ip", "ip地址");
  28. // 默认的,未添加alias的属性也会写出,如果想只写出加了别名的字段,可以调用此方法排除之
  29. writer.setOnlyAlias(true);
  30. //一次性写出内容,强制输出标题
  31. writer.write(rows11);
  32. writer.close();

结果

image.png

解决办法

因为我们有一个方法 可以获取到 所有的标题
这样我们在每次map 填充之前 先对所有属性进行赋值为i空 然后 再取替换

  1. HashMap<String, Object> data = new HashMap<>(32);
  2. //填充所有属性 防止excel 生成 错位
  3. tableTileList.forEach(e->{
  4. data.put(e.getProp(),null);
  5. });
  6. for (Field field : reportCompose.getClass().getDeclaredFields()) {
  7. if (field.getType().equals(List.class)) {
  8. for (OrgExMngExceptionReportItems item : reportCompose.getReportItemsList()) {
  9. data.put(item.getItemCode(), itemValueConverter(item.getItemValue()));
  10. }
  11. } else {
  12. Object value = ReflectUtil.getFieldValue(reportCompose, field.getName());
  13. if (ObjectUtil.isNotNull(value)) {
  14. data.put(field.getName(), value);
  15. }
  16. }
  17. }