EasyExcel根据列值是否相等导出动态设置指定单元格CellStyle字体颜色,背景等

     <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.2.1</version>
     </dependency>
    public static void init(HttpServletResponse response, String name) {
        try {
            response.setContentType(
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode(name, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition",
                "attachment;filename*=utf-8''" + fileName + ".xlsx");
        } catch (Exception ex) {
            log.warn("导出初始化失败,err={}", ex.getMessage());
        }
    }

首先,创建一个CustomWriteHandler类实现WriteHandler接口,在这个类中定义如何根据单元格值来改变CellStyle: 

package com.canyue.guoyan.service.converter;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.ruoyi.common.utils.StringUtils;
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.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;

import java.util.List;

@Slf4j
public class CustomWriteHandler implements CellWriteHandler {


    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        if (isHead) {
            return;
        }
        Workbook workbook = writeSheetHolder.getSheet().getWorkbook();
        Row row = cell.getRow();
        //比较列1
        Cell rowPurchaseNum = row.getCell(14);
        //比较列2
        Cell rowSingNum = row.getCell(19);
        Cell rowSignAmount = row.getCell(20);
        CellStyle cellStyle = workbook.createCellStyle();
        if (rowPurchaseNum != null && rowSingNum != null && rowSignAmount!=null &&
                StringUtils.isNotBlank(rowPurchaseNum.getStringCellValue())&&
                StringUtils.isNotBlank(rowSingNum.getStringCellValue()) &&
                StringUtils.isNotBlank(rowSignAmount.getStringCellValue())&&
                !rowPurchaseNum.getStringCellValue().equals(rowSingNum.getStringCellValue())) {
            //背景颜色
            cellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
            //填充色纯色
            cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            Font font = workbook.createFont();
            //字体颜色
            font.setColor(IndexedColors.RED.getIndex());
            cellStyle.setFont(font);
            rowSingNum.setCellStyle(cellStyle);
            rowSignAmount.setCellStyle(cellStyle);
        } else {
            cellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
            cellStyle.setFillPattern(FillPatternType.NO_FILL);
            Font font = workbook.createFont();
            font.setColor(IndexedColors.BLACK.getIndex());
            cellStyle.setFont(font);
        }
        cell.setCellStyle(cellStyle);

    }
}

然后,在写入Excel的时候,注册这个handler: 


    public void export(HttpServletResponse response, List<WorkbenchOrderDataExcel> collectDataExcels, String fileName) {
        try {
            ExcelUtils.init(response, fileName);
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
            WriteFont headWriteFont = new WriteFont();
            conHead(headWriteCellStyle, headWriteFont);
            EasyExcel.write(response.getOutputStream(), WorkbenchOrderDataExcel.class)
                    .registerWriteHandler(new WorkbenchCellStyleHandler())
                    .autoCloseStream(Boolean.TRUE).sheet(fileName)
                    .doWrite(collectDataExcels);
        } catch (Exception e) {
            log.error("导出" + fileName + "错误", e);
        }
    }

在上面的代码中,WorkbenchOrderDataExcel应该替换为你的数据模型类,dataList是包含你的数据模型实例的列表,fileName是生成的Excel文件的名称。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值