工具代码:
public static void generateDynamicHeadExcel(String filePath, List<String> sheetNames, Map<String,
List<List<String>>> headMap, Map<String,List<List<Object>>> contentMap){
ExcelWriter excelWriter = EasyExcel
.write(filePath)
.excelType(DEFAULT_EXCEL_TYPE)
.autoCloseStream(Boolean.TRUE)
.registerConverter(new LongStringConverter())
.build();
for (int i=0, j=sheetNames.size(); i<j; i++){
String sheetName = sheetNames.get(i);
List<List<String>> head = headMap.get(sheetName);
List<List<Object>> content = contentMap.get(sheetName);
WriteSheet writeSheet = EasyExcel.writerSheet(i, sheetName).head(head).build();
excelWriter.write(content, writeSheet);
}
excelWriter.finish();
}
测试代码:
public static void main(String[] args){
List<String> sheetNames = Stream.of("sheet1", "sheet2").collect(Collectors.toList());
Map<String, List<List<String>>> headMap = new HashMap<>();
List<String> inList1 = Stream.of("tab1").collect(Collectors.toList());
List<String> inList2 = Stream.of("tab2").collect(Collectors.toList());
List<List<String>> list1 = Stream.of(inList1, inList2).collect(Collectors.toList());
headMap.put(sheetNames.get(0), list1);
List<String> inList3 = Stream.of("tab3").collect(Collectors.toList());
List<String> inList4 = Stream.of("tab4").collect(Collectors.toList());
List<List<String>> list2 = Stream.of(inList3, inList4).collect(Collectors.toList());
headMap.put(sheetNames.get(1), list2);
Map<String, List<List<Object>>> contentMap = new HashMap<>();
List<List<Object>> list3 = new ArrayList<>();
list3.add(Stream.of("content1", "content2").collect(Collectors.toList()));
contentMap.put(sheetNames.get(0), list3);
List<List<Object>> list4 = new ArrayList<>();
list4.add(Stream.of("content3", "content4").collect(Collectors.toList()));
contentMap.put(sheetNames.get(1), list4);
EasyExcelUtil.generateDynamicHeadExcel("c://tempDir/123.xlsx", sheetNames, headMap, contentMap);
}