动态导出分为三种:

  • 动态指定标题、字段顺序;
  • 字段分组;
  • Map导出;

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

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

2.字段分组

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

  1. @ExcelColumn(title="姓名",groups={People.class})String name;

  2. @ExcelColumn(title="年龄")String age;

  3. 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.  
  5. List<Map<String, Object>> dataMapList = new ArrayList<>();
  6. Map<String, Object> v1 = new HashMap<>();
  7. v1.put("a", "数据a1");
  8. v1.put("b", 3);
  9.  
  10. Map<String, Object> v2 = new HashMap<>();
  11. v2.put("a", "数据a2");
  12. v2.put("b", 5);
  13.  
  14. dataMapList.add(v1);
  15. dataMapList.add(v2);
  16.  
  17. List<String> titles = new ArrayList(headerMap.values());
  18. List<String> orders = new ArrayList(headerMap.keySet());
  19. Workbook workbook = DefaultExcelBuilder.getInstance()
  20. .sheetName("sheet1")
  21. .titles(titles)
  22. .widths(10,20)
  23. .fieldDisplayOrder(orders)
  24. .build(dataMapList);
  25. FileExportUtil.export(workbook, new File("/tmp/zz.xlsx"));

widths方法目前只能运用于Map导出