自定义处理器
`
package com.ruoyi.web.part.service.impl;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.util.BooleanUtils;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import java.util.List;
import java.util.Map;
/**
-
功能描述: 动态设置行背景色
-
@version v 1.0
-
@Author:
-
@Date: 2024-06-12 19:08
*/
public class RowBackGroundWriteHandler implements CellWriteHandler {/**
- key:行下标集合,value:背景色
*/
private final Map<List, Short> rowBackColor;
public RowBackGroundWriteHandler(Map<List
, Short> rowBackColor) {
this.rowBackColor = rowBackColor;
}@Override
public void beforeCellCreate(CellWriteHandlerContext context) {
}@Override
public void afterCellDispose(CellWriteHandlerContext context) {
if (BooleanUtils.isNotTrue(context.getHead())) {
// 当前行号
Integer currentRowIndex = context.getRowIndex();
for (Map.Entry<List, Short> next : rowBackColor.entrySet()) {
ListrowIndex = next.getKey();
Short colorIndex = next.getValue();
if (rowIndex.contains(currentRowIndex)) {
WriteCellData<?> cellData = context.getFirstCellData();
WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
// 设置颜色
writeCellStyle.setFillForegroundColor(colorIndex);
writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
}
}}
}
- key:行下标集合,value:背景色
}
`
输出Excel
Map<List<Integer>, Short> rowBackColor = new HashMap<>(); rowBackColor.put(Collections.singletonList(1), IndexedColors.CORAL.index); rowBackColor.put(Collections.singletonList(2), IndexedColors.YELLOW.index); rowBackColor.put(Collections.singletonList(3), IndexedColors.GREEN.index); RowBackGroundWriteHandler handler = new RowBackGroundWriteHandler(rowBackColor); WriteSheet writeSheet = EasyExcel.writerSheet(0, "sheet") .registerWriteHandler(handler) .head(DownAllAnalyze.class) .build(); excelWriter.write(exportList, writeSheet);