package com.ruoyi.inspect.excel.handler; import com.alibaba.excel.write.handler.SheetWriteHandler; import com.alibaba.excel.write.handler.context.SheetWriteHandlerContext; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Collections; import java.util.List; /** * 人员考勤导出动态表头处理器 */ public class StaffAttendanceHeaderWriteHandler implements SheetWriteHandler { private static final int TITLE_ROW_INDEX = 1; private static final int WEEK_ROW_INDEX = 2; private static final int DAY_ROW_INDEX = 3; private static final int START_COLUMN_INDEX = 2; private static final int MAX_DATE_COLUMN_COUNT = 31; private static final DateTimeFormatter TITLE_FORMATTER = DateTimeFormatter.ofPattern("yyyy年M月"); private final List attendanceDateList; public StaffAttendanceHeaderWriteHandler(List attendanceDateList) { this.attendanceDateList = attendanceDateList == null ? Collections.emptyList() : attendanceDateList; } @Override public void afterSheetCreate(SheetWriteHandlerContext context) { Sheet sheet = context.getWriteSheetHolder().getSheet(); if (sheet == null || attendanceDateList.isEmpty()) { return; } Row titleRow = sheet.getRow(TITLE_ROW_INDEX); if (titleRow != null) { Cell titleCell = titleRow.getCell(0); if (titleCell != null) { titleCell.setCellValue(attendanceDateList.get(attendanceDateList.size() - 1).format(TITLE_FORMATTER)); } } Row weekRow = sheet.getRow(WEEK_ROW_INDEX); Row dayRow = sheet.getRow(DAY_ROW_INDEX); if (weekRow == null || dayRow == null) { return; } for (int i = 0; i < MAX_DATE_COLUMN_COUNT; i++) { Cell weekCell = getOrCreateCell(weekRow, START_COLUMN_INDEX + i); Cell dayCell = getOrCreateCell(dayRow, START_COLUMN_INDEX + i); if (i < attendanceDateList.size()) { LocalDate currentDate = attendanceDateList.get(i); weekCell.setCellValue(resolveWeekOfYear(currentDate)); dayCell.setCellValue(currentDate.getDayOfMonth()); } else { weekCell.setBlank(); dayCell.setBlank(); } } } private Cell getOrCreateCell(Row row, int cellIndex) { Cell cell = row.getCell(cellIndex); if (cell != null) { return cell; } Cell templateCell = row.getCell(START_COLUMN_INDEX); cell = row.createCell(cellIndex); if (templateCell != null && templateCell.getCellStyle() != null) { cell.setCellStyle(templateCell.getCellStyle()); } return cell; } private String resolveWeekOfYear(LocalDate date) { switch (date.getDayOfWeek()) { case MONDAY: return "一"; case TUESDAY: return "二"; case WEDNESDAY: return "三"; case THURSDAY: return "四"; case FRIDAY: return "五"; case SATURDAY: return "六"; case SUNDAY: return "日"; default: return ""; } } }