动态导出分为三种:
- 动态指定标题、字段顺序;
- 字段分组;
- Map导出;
1.动态指定标题、字段顺序
- // title
- List<String> titles = new ArrayList<>();
- titles.add("姓名");
- titles.add("年龄");
- // field display order
- List<String> order = new ArrayList<>();
- order.add("name");
- order.add("age");
- // display data
- List<TestDO> dataList = this.getData();
- Workbook workbook = DefaultExcelBuilder.getInstance()
- .sheetName("default example")
- .titles(titles)
- .fieldDisplayOrder(order)
- .build(dataList);
- private List<TestDO> getData(){
- TestDO testDO = new TestDO();
- testDO.setName("张三");
- TestDO testDO1 = new TestDO();
- testDO1.setName("李四");
- TestDO testDO2 = new TestDO();
- testDO2.setName("王五");
- testDO2.setAge(15);
- TestDO testDO3 = new TestDO();
- testDO3.setName("陈六");
- testDO3.setAge(25);
- List<TestDO> dataList = new ArrayList<>();
- dataList.add(testDO);
- dataList.add(testDO1);
- dataList.add(testDO2);
- dataList.add(testDO3);
- return dataList;
- }
2.字段分组
该种方式基于注解@ExcelColumn的groups属性
- @ExcelColumn(title="姓名",groups={People.class})String name;
@ExcelColumn(title="年龄")String age;
DefaultExcelBuilder.of(ArtCrowd.class).build(People.class);
上述示例将只导出姓名
字段
3.Map导出
- Map<String, String> headerMap = new HashMap<>();
- headerMap.put("a", "测试A");
- headerMap.put("b", "测试B");
- List<Map<String, Object>> dataMapList = new ArrayList<>();
- Map<String, Object> v1 = new HashMap<>();
- v1.put("a", "数据a1");
- v1.put("b", 3);
- Map<String, Object> v2 = new HashMap<>();
- v2.put("a", "数据a2");
- v2.put("b", 5);
- dataMapList.add(v1);
- dataMapList.add(v2);
- List<String> titles = new ArrayList(headerMap.values());
- List<String> orders = new ArrayList(headerMap.keySet());
- Workbook workbook = DefaultExcelBuilder.getInstance()
- .sheetName("sheet1")
- .titles(titles)
- .widths(10,20)
- .fieldDisplayOrder(orders)
- .build(dataMapList);
- FileExportUtil.export(workbook, new File("/tmp/zz.xlsx"));
widths方法目前只能运用于Map导出