动态导出分为三种:

  1. 动态指定标题、字段顺序;
  2. 字段分组;
  3. Map导出;

1.动态指定标题、字段顺序

  1. // title
  2. List<String> titles = new ArrayList<>();
  3. titles.add("姓名");
  4. titles.add("年龄");
  5. // field display order
  6. List<String> order = new ArrayList<>();
  7. order.add("name");
  8. order.add("age");
  9. // display data
  10. List<TestDO> dataList = this.getData();
  11. Workbook workbook = DefaultExcelBuilder.of(TestDO.class)
  12. .sheetName("default example")
  13. .titles(titles)
  14. .fieldDisplayOrder(order)
  15. .build(dataList);
  16. private List<TestDO> getData(){
  17. TestDO testDO = new TestDO();
  18. testDO.setName("张三");
  19. TestDO testDO1 = new TestDO();
  20. testDO1.setName("李四");
  21. TestDO testDO2 = new TestDO();
  22. testDO2.setName("王五");
  23. testDO2.setAge(15);
  24. TestDO testDO3 = new TestDO();
  25. testDO3.setName("陈六");
  26. testDO3.setAge(25);
  27. List<TestDO> dataList = new ArrayList<>();
  28. dataList.add(testDO);
  29. dataList.add(testDO1);
  30. dataList.add(testDO2);
  31. dataList.add(testDO3);
  32. return dataList;
  33. }

2.字段分组

该种方式基于注解@ExcelColumn的groups属性

  1. @ExcelColumn(title="姓名",groups={People.class})
  2. String name;
  3. @ExcelColumn(title="年龄")
  4. String age;
  5. DefaultExcelBuilder.of(ArtCrowd.class).build(People.class);

上述示例将只导出姓名字段

3.Map导出

  1. Map<String, String> headerMap = new HashMap<>();
  2. headerMap.put("a", "测试A");
  3. headerMap.put("b", "测试B");
  4. List<Map> dataMapList = new ArrayList<>();
  5. Map<String, Object> v1 = new HashMap<>();
  6. v1.put("a", "数据a1");
  7. v1.put("b", 3);
  8. Map<String, Object> v2 = new HashMap<>();
  9. v2.put("a", "数据a2");
  10. v2.put("b", 5);
  11. dataMapList.add(v1);
  12. dataMapList.add(v2);
  13. List<String> titles = new ArrayList(headerMap.values());
  14. List<String> orders = new ArrayList(headerMap.keySet());
  15. Workbook workbook = DefaultExcelBuilder.of(Map.class)
  16. .sheetName("sheet1")
  17. .titles(titles)
  18. .widths(10,20)
  19. .fieldDisplayOrder(orders)
  20. .build(dataMapList);
  21. FileExportUtil.export(workbook, new File("/tmp/zz.xlsx"));

Map导出默认不支持格式化,需自行格式化,如需指定Map中value类型,如超链接等,value需设置如下:

  1. import com.github.liaochong.myexcel.core.constant.LinkUrl;
  2. import com.github.liaochong.myexcel.core.container.Pair;
  3. Map<String, Object> obj = new HashMap<>();
  4. obj.put("2", Pair.of(LinkUrl.class,"http://www.baidu.com"));