easyexcel指定sheet页动态给行列加背景色

需求

1、easyexcel,有多个sheet页,某些sheet页的行、列动态需要加背景色。

2、扩展支持cellStyle标记单元格超过64000

复制代码
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.util.HashMap;
import java.util.List;
复制代码
@Slf4j
public class ExcelBackgroudHandler implements CellWriteHandler {
复制代码
//颜色
private Short colorIndex;

//行,以及对应的列,多个列逗号拼接
private HashMap<Integer,String> rowColMap;

//保存单元格样式,否则cellStyle被创建超过64000就会报错
Map<String,CellStyle> cellStyleMap = new HashMap<>();
复制代码
    public ExcelBackgroudHandler(Short colorIndex, HashMap<Integer, String> rowColMap) {
        this.colorIndex = colorIndex;
        this.rowColMap = rowColMap;
    }


    @Override
    public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
                                 Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {
    }

    @Override
    public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell,
                                Head head, Integer relativeRowIndex, Boolean isHead) {
    }

    @Override
    public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
                                       CellData cellData, Cell cell, Head head, Integer relativeRowIndex,
                                       Boolean isHead) {

    }

    /***
     * 指定行列加颜色
     * @param writeSheetHolder
     * @param writeTableHolder
     * @param cellDataList
     * @param cell
     * @param head
     * @param relativeRowIndex
     * @param isHead

     * @Date: 2023/11/22 17:02
    **/
    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
                                 List<CellData> cellDataList, Cell cell, Head head,
                                 Integer relativeRowIndex, Boolean isHead) {
        int columIndex = cell.getColumnIndex();
        int rowIndex = cell.getRowIndex();
        if (null != rowColMap && rowColMap.get(rowIndex)!=null && rowColMap.get(rowIndex).contains(columIndex+"")) {
            Sheet sheet = writeSheetHolder.getSheet();
            Workbook workbook = sheet.getWorkbook();
            CellStyle cellStyle;
            String key = colorIndex+"";
            if(cellStyleMap.get(key )!=null){
                cellStyle = cellStyleMap.get(key );
            }else{
                cellStyle = workbook.createCellStyle();
                cellStyle.setFillForegroundColor(colorIndex);
                // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND
                cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                cellStyleMap.put(key ,cellStyle);
            }
            cell.setCellStyle(cellStyle );
        }
    }



}
复制代码
@Data
public class TestVO {


    @ExcelProperty(value = "姓名", index = 0)
    private String name;


    @ExcelProperty(value = "年龄", index = 1)
    private int age;

    @ExcelProperty(value = "学校", index = 2)
    private String school;


}

测试类

复制代码
/**
 * 测试导出模板
 * 1. 标题指定某列标红色字段
 * 2. 标题指定某列加批注
 */
public static void main(String[] args) throws FileNotFoundException {
    String filePahth = "D:\\1.xlsx";
    // 输出流
    OutputStream outputStream = new FileOutputStream(new File(filePahth));
    // 导出的数据
    List<TestVO> dataList = new ArrayList<>();
    for(int i=0;i<35000;i++){
        TestVO testVO = new TestVO();
        testVO.setAge(11);
        testVO.setName("测试dd"+i);
        testVO.setSchool("学校"+i);
        TestVO testVO1 = new TestVO();
        testVO1.setAge(111);
        testVO1.setName("测试1"+i);
        testVO1.setSchool("学校1"+i);
        dataList.add(testVO);
        dataList.add(testVO1);
    }

    // 指定批注
    HashMap<Integer, String> annotationsMap = new HashMap<>();
    for(int i=0;i<70000;i++){
        annotationsMap.put(i,"1,2");
    }
    ExcelBackgroudHandler excelBackgroudHandler = new ExcelBackgroudHandler(IndexedColors.RED.index,annotationsMap);
    WriteSheet writeSheet = EasyExcel.writerSheet(1, "测试")
            .registerWriteHandler(excelBackgroudHandler).head(TestVO.class).build();
    WriteSheet writeSheet2 = EasyExcel.writerSheet(2, "测试2")
            .registerWriteHandler(excelBackgroudHandler).head(TestVO.class).build();
    ExcelWriter excelWriter = EasyExcel.write(outputStream).build();
    excelWriter.write(dataList,writeSheet);
    excelWriter.write(dataList,writeSheet2);
    excelWriter.finish();

    //excel追加导出
    String newFilePath = "D:\\1temp.xlsx";
    ExcelWriter excelWriter1 = EasyExcel.write(newFilePath).withTemplate(filePahth).build();
    WriteSheet writeSheet1 = EasyExcel.writerSheet(2, "测试1") .head(TestVO.class).build();
    excelWriter1.write(dataList,writeSheet1);
    excelWriter1.finish();
    File tempFile = new File(newFilePath);
    if (tempFile.exists()) {
        File file = new File(filePahth);
        file.delete();
        tempFile.renameTo(file);
    }


}
相关推荐
五岳1 小时前
分库分表数据源ShardingSphereDataSource的Connection元数据误用问题分析
java·mysql·爬坑
带刺的坐椅1 小时前
迈向 MCP 集群化:Solon AI (支持 Java8+)在解决 MCP 服务可扩展性上的探索与实践
java·ai·llm·solon·mcp
鼠爷ねずみ1 小时前
SpringCloud前后端整体开发流程-以及技术总结文章实时更新中
java·数据库·后端·spring·spring cloud
代码or搬砖2 小时前
String字符串
android·java·开发语言
AM越.3 小时前
Java设计模式详解--装饰器设计模式(含uml图)
java·设计模式·uml
5980354153 小时前
【java工具类】小数、整数转中文大写
android·java·开发语言
JIngJaneIL4 小时前
基于java + vue个人博客系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
吃喝不愁霸王餐APP开发者4 小时前
Java后端服务在对接全国性霸王餐API时的多数据中心部署与就近调用策略
java·开发语言
从心归零4 小时前
springboot-jpa的批量更新方法
java·spring boot·spring