首页 > 其他分享 >EasyExcel动态设置行背景色

EasyExcel动态设置行背景色

时间:2024-06-12 20:14:05浏览次数:17  
标签:Map Short rowBackColor EasyExcel 背景色 context import 动态 com

自定义处理器

`
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()) {
    List rowIndex = 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);
    }
    }

     }
    

    }

}

`

输出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);

标签:Map,Short,rowBackColor,EasyExcel,背景色,context,import,动态,com
From: https://www.cnblogs.com/jie-blog/p/18244609

相关文章