easyExcel 实现动态表头

问题

根据时间段条件(如2020-01-01到2020-03-01)进行excel表格导出,导出的格式如下图 图1,橙色部分是固定表头,绿色部分是可更具时间段变化横向拓展的动态表头,目前获取到的数据是一个List 列表 ,ExportData中包含一个MonthData列表,具体类属性结构下图 图2,怎样实现这种动态的表格类型的导出?

涉及技术:easyexcel 、java 、springboot

图1

img

图2

img

可以实现poi实现,类似下面这种,给你提供下思路

// 生成表头数据
List headers = new ArrayList<>();
headers.add("客户名称");
headers.add("客户编号");
headers.add("公司地址");
headers.add("联系人");
headers.add("联系电话");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
Calendar startCal = Calendar.getInstance();
startCal.setTime(dateFormat.parse("2020-01"));
Calendar endCal = Calendar.getInstance();
endCal.setTime(dateFormat.parse("2020-03"));
while(startCal.before(endCal) || startCal.equals(endCal)) {
    headers.add(dateFormat.format(startCal.getTime()));
    startCal.add(Calendar.MONTH, 1);
}

// 将表头添加到表格中
Row headerRow = sheet.createRow(0);
for(int i = 0; i < headers.size(); i++) {
    Cell cell = headerRow.createCell(i);
    cell.setCellValue(headers.get(i));
    if(i < 5) {
        cell.setCellStyle(fixedHeaderStyle);
    } else {
        cell.setCellStyle(dynamicHeaderStyle);
    }
}

// 遍历MonthData列表,将数据填充到单元格中
List monthDataList = exportData.getMonthDataList();
int rowIndex = 1;
for(ExportData.MonthData monthData : monthDataList) {
    Row row = sheet.createRow(rowIndex++);
    row.createCell(0).setCellValue(monthData.getCustomerName());
    row.createCell(1).setCellValue(monthData.getCustomerNumber());
    row.createCell(2).setCellValue(monthData.getCompanyAddress());
    row.createCell(3).setCellValue(monthData.getContactName());
    row.createCell(4).setCellValue(monthData.getContactNumber());
    Map dataMap = monthData.getDataMap();
    int cellIndex = 5;
    for(String key : headers.subList(5, headers.size())) {
        Cell cell = row.createCell(cellIndex++);
        Double value = dataMap.get(key);
        if(value != null) {
            cell.setCellValue(value);
        }
    }
}