public class ExcelRowColorHandler implements CellWriteHandler {
private final Integer columnIndex;
private final Set<Integer> redRowIndex;
private final Set<Integer> yellowRowIndex;
private final Set<Integer> greenRowIndex;
public ExcelRowColorHandler(Integer columnIndex, Set<Integer> redRowIndex, Set<Integer> yellowRowIndex, Set<Integer> greenRowIndex) {
this.columnIndex = columnIndex;
this.redRowIndex = redRowIndex;
this.yellowRowIndex = yellowRowIndex;
this.greenRowIndex = greenRowIndex;
}
@Override
public void beforeCellCreate(CellWriteHandlerContext context) {
// Row in source code context to be optimized: supports parameter input to obtain the number of
// occurrences of the required field and set the background color
// to do:(row.getCell(columnIndex)lose efficacy)
}
@Override
public void afterCellDispose(CellWriteHandlerContext context) {
if (BooleanUtils.isNotTrue(context.getHead())) {
Integer currentRowIndex = context.getRowIndex();
Integer currentColumnIndex = context.getColumnIndex();
//最后一列,(备注信息)设置颜色
if (currentColumnIndex.equals(columnIndex - 1)) {
WriteCellData<?> cellData = context.getFirstCellData();
WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
//根据数据内容,设置不同字体颜色
if (!Objects.isNull(redRowIndex) && redRowIndex.contains(currentRowIndex)) {
WriteFont font = new WriteFont();
font.setColor(IndexedColors.RED.getIndex());
writeCellStyle.setWriteFont(font);
} else if (!Objects.isNull(yellowRowIndex) && yellowRowIndex.contains(currentRowIndex)) {
WriteFont font = new WriteFont();
font.setColor(IndexedColors.YELLOW.getIndex());
writeCellStyle.setWriteFont(font);
} else if (!Objects.isNull(greenRowIndex) && greenRowIndex.contains(currentRowIndex)) {
WriteFont font = new WriteFont();
font.setColor(IndexedColors.GREEN.getIndex());
writeCellStyle.setWriteFont(font);
}
}
}
}
}