EasyExcel 批量设置单元格样式(字体样式、背景颜色、边框样式、对齐方式、自动换行)

本文介绍了如何使用Maven配置Hutool和EasyExcel工具来处理Excel文档,并展示了CellStyleModel类,用于定义单元格的字体、颜色、边框和对齐方式等样式。同时,CustomCellStyleHandler类作为自定义单元格样式处理器,支持字体、背景、边框和对齐方式的设置。通过示例代码,演示了如何导出包含这些样式的Excel文件。
摘要由CSDN通过智能技术生成

1、Maven配置

        <!--hutool工具包-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.5.1</version>
        </dependency>
        <!-- EasyExcel文档处理工具 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.2.8</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

2、CellStyleModel
样式信息类。

package com.easyexcel.model;
 
import cn.hutool.core.util.StrUtil;
import lombok.Data;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.DefaultIndexedColorMap;
import org.apache.poi.xssf.usermodel.XSSFColor;
 
/**
 * 样式信息类
 */
@Data
public class CellStyleModel {
    /**
     * sheet名称
     */
    private String sheetName;
    /**
     * 列索引
     */
    private int colIndex;
    /**
     * 行索引
     */
    private int rowIndex;
    /**
     * 字体名称
     */
    private String fontName;
    /**
     * 字体大小
     */
    private Double fontHeight;
    /**
     * 字体颜色
     */
    private Object fontColor;
    /**
     * 字体加粗
     */
    private Boolean fontBold;
    /**
     * 字体斜体
     */
    private Boolean fontItalic;
    /**
     * 字体下划线
     */
    private Byte fontUnderLine;
    /**
     * 字体上标下标
     */
    private Short fontTypeOffset;
    /**
     * 字体删除线
     */
    private Boolean fontStrikeout;
    /**
     * 背景颜色
     */
    private Object backgroundColor;
 
    /**
     * 上边框线条类型
     */
    private BorderStyle borderTop;
    /**
     * 右边框线条类型
     */
    private BorderStyle borderRight;
    /**
     * 下边框线条类型
     */
    private BorderStyle borderBottom;
    /**
     * 左边框线条类型
     */
    private BorderStyle borderLeft;
    /**
     * 上边框线条颜色
     */
    private Object topBorderColor;
    /**
     * 上边框线条颜色
     */
    private Object rightBorderColor;
    /**
     * 下边框线条颜色
     */
    private Object bottomBorderColor;
    /**
     */
    private Object leftBorderColor;
    /**
     * 水平对齐方式
     */
    private HorizontalAlignment horizontalAlignment;
    /**
     * 垂直对齐方式
     */
    private VerticalAlignment verticalAlignment;
    /**
     * 自动换行方式
     */
    private Boolean wrapText;
 
    /**
     * 生成字体名称样式信息
     *
     * @param sheetName   sheet页名称
     * @param rowIndex    行号
     * @param columnIndex 列号
     * @param fontName    字体名称(默认宋体)
     * @return
     */
    public static CellStyleModel createFontNameCellStyleModel(String sheetName, int rowIndex, int columnIndex, String fontName) {
        return createFontCellStyleModel(sheetName, rowIndex, columnIndex, fontName, null, null, null, null, null, null, null);
    }
 
    /**
     * 生成字体名称大小信息
     *
     * @param sheetName   sheet页名称
     * @param rowIndex    行号
     * @param columnIndex 列号
     * @param fontHeight  字体大小
     * @return
     */
    public static CellStyleModel createFontHeightCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , Double fontHeight) {
        return createFontCellStyleModel(sheetName, rowIndex, columnIndex, null, fontHeight, null, null, null, null, null, null);
    }
 
    /**
     * 得到RBG自定义颜色
     *
     * @param redNum   红色数值
     * @param greenNum 绿色数值
     * @param blueNum  蓝色数值
     * @return
     */
    public static XSSFColor getRGBColor(int redNum, int greenNum, int blueNum) {
        XSSFColor color = new XSSFColor(new byte[]{(byte) redNum, (byte) greenNum, (byte) blueNum}, new DefaultIndexedColorMap());
        return color;
    }
 
    /**
     * 生成字体颜色样式信息(支持自定义RGB颜色)
     *
     * @param sheetName   sheet页名称
     * @param rowIndex    行号
     * @param columnIndex 列号
     * @param redNum      红色数值
     * @param greenNum    绿色数值
     * @param blueNum     蓝色数值
     * @return
     */
    public static CellStyleModel createFontColorCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , int redNum, int greenNum, int blueNum) {
        XSSFColor fontColor = getRGBColor(redNum, greenNum, blueNum);
        return createFontColorCellStyleModel(sheetName, rowIndex, columnIndex, fontColor);
    }
 
    /**
     * 生成字体颜色样式信息
     *
     * @param sheetName   sheet页名称
     * @param rowIndex    行号
     * @param columnIndex 列号
     * @param fontColor   字体颜色
     * @return
     */
    public static CellStyleModel createFontColorCellStyleModel(String sheetName, int rowIndex, int columnIndex, Object fontColor) {
        return createFontCellStyleModel(sheetName, rowIndex, columnIndex, null, null, fontColor, null, null, null, null, null);
    }
 
    /**
     * 生成字体加粗样式信息
     *
     * @param sheetName   sheet页名称
     * @param rowIndex    行号
     * @param columnIndex 列号
     * @param fontBold    字体加粗
     * @return
     */
    public static CellStyleModel createFontBoldCellStyleModel(String sheetName, int rowIndex, int columnIndex, Boolean fontBold) {
        return createFontCellStyleModel(sheetName, rowIndex, columnIndex, null, null, null, fontBold, null, null, null, null);
    }
 
    /**
     * 生成字体斜体样式信息
     *
     * @param sheetName   sheet页名称
     * @param rowIndex    行号
     * @param columnIndex 列号
     * @param fontItalic  字体斜体
     * @return
     */
    public static CellStyleModel createFontItalicCellStyleModel(String sheetName, int rowIndex, int columnIndex, Boolean fontItalic) {
        return createFontCellStyleModel(sheetName, rowIndex, columnIndex, null, null, null, null, fontItalic, null, null, null);
    }
 
    /**
     * 生成字体下划线样式信息
     *
     * @param sheetName     sheet页名称
     * @param rowIndex      行号
     * @param columnIndex   列号
     * @param fontUnderLine 字体下划线
     * @return
     */
    public static CellStyleModel createFontUnderLineCellStyleModel(String sheetName, int rowIndex, int columnIndex, Byte fontUnderLine) {
        return createFontCellStyleModel(sheetName, rowIndex, columnIndex, null, null, null, null, null, fontUnderLine, null, null);
    }
 
    /**
     * 生成字体上标下标样式信息
     *
     * @param sheetName      sheet页名称
     * @param rowIndex       行号
     * @param columnIndex    列号
     * @param fontTypeOffset 字体上标下标
     * @return
     */
    public static CellStyleModel createFontTypeOffsetCellStyleModel(String sheetName, int rowIndex, int columnIndex, Short fontTypeOffset) {
        return createFontCellStyleModel(sheetName, rowIndex, columnIndex, null, null, null, null, null, null, fontTypeOffset, null);
    }
 
    /**
     * 生成字体删除线样式信息
     *
     * @param sheetName     sheet页名称
     * @param rowIndex      行号
     * @param columnIndex   列号
     * @param fontStrikeout 字体删除线
     * @return
     */
    public static CellStyleModel createFontStrikeoutCellStyleModel(String sheetName, int rowIndex, int columnIndex, Boolean fontStrikeout) {
        return createFontCellStyleModel(sheetName, rowIndex, columnIndex, null, null, null, null, null, null, null, fontStrikeout);
    }
 
    /**
     * 生成字体样式信息
     *
     * @param sheetName      sheet页名称
     * @param rowIndex       行号
     * @param columnIndex    列号
     * @param fontName       字体名称(默认宋体)
     * @param fontHeight     字体大小
     * @param fontColor      字体颜色
     * @param fontBold       字体加粗
     * @param fontItalic     字体斜体
     * @param fontUnderLine  字体下划线
     * @param fontTypeOffset 字体上标下标
     * @param fontStrikeout  字体删除线
     * @return
     */
    public static CellStyleModel createFontCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , String fontName, Double fontHeight, Object fontColor, Boolean fontBold, Boolean fontItalic, Byte fontUnderLine
            , Short fontTypeOffset, Boolean fontStrikeout) {
        return createCellStyleModel(sheetName, rowIndex, columnIndex, fontName, fontHeight, fontColor, fontBold, fontItalic
                , fontUnderLine, fontTypeOffset, fontStrikeout, null);
    }
 
    /**
     * 生成背景颜色样式信息
     *
     * @param sheetName       sheet页名称
     * @param rowIndex        行号
     * @param columnIndex     列号
     * @param backgroundColor 背景颜色
     * @return
     */
    public static CellStyleModel createBackgroundColorCellStyleModel(String sheetName, int rowIndex, int columnIndex, Object backgroundColor) {
        return createCellStyleModel(sheetName, rowIndex, columnIndex, null, null, null, null, null, null, null, null, backgroundColor);
    }
 
    /**
     * 生成背景颜色样式信息(支持自定义RGB颜色)
     *
     * @param sheetName   sheet页名称
     * @param rowIndex    行号
     * @param columnIndex 列号
     * @param redNum      红色数值
     * @param greenNum    绿色数值
     * @param blueNum     蓝色数值
     * @return
     */
    public static CellStyleModel createBackgroundColorCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , int redNum, int greenNum, int blueNum) {
        XSSFColor backgroundColor = getRGBColor(redNum, greenNum, blueNum);
        return createBackgroundColorCellStyleModel(sheetName, rowIndex, columnIndex, backgroundColor);
    }
 
    /**
     * 生成样式信息
     *
     * @param sheetName       sheet页名称
     * @param rowIndex        行号
     * @param columnIndex     列号
     * @param fontName        字体名称(宋体)
     * @param fontHeight      字体大小
     * @param fontColor       字体颜色
     * @param fontBold        字体加粗
     * @param fontItalic      字体斜体
     * @param fontUnderLine   字体下划线
     * @param fontTypeOffset  字体上标下标
     * @param fontStrikeout   字体删除线
     * @param backgroundColor 背景颜色
     * @return
     */
    public static CellStyleModel createCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , String fontName, Double fontHeight, Object fontColor, Boolean fontBold, Boolean fontItalic, Byte fontUnderLine
            , Short fontTypeOffset, Boolean fontStrikeout, Object backgroundColor) {
        return createCellStyleModel(sheetName, rowIndex, columnIndex, fontName, fontHeight, fontColor, fontBold, fontItalic
                , fontUnderLine, fontTypeOffset, fontStrikeout, backgroundColor, null, null, null, null, null, null, null, null);
    }
 
    /**
     * 生成上边框线条颜色样式信息
     *
     * @param sheetName      sheet页名称
     * @param rowIndex       行号
     * @param columnIndex    列号
     * @param topBorderColor 上边框线条颜色
     * @return
     */
    public static CellStyleModel createTopBorderColorCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , Object topBorderColor) {
        return createBorderColorCellStyleModel(sheetName, rowIndex, columnIndex, topBorderColor, null, null, null);
    }
 
    /**
     * 生成右边框线条颜色样式信息
     *
     * @param sheetName        sheet页名称
     * @param rowIndex         行号
     * @param columnIndex      列号
     * @param rightBorderColor 右边框线条颜色
     * @return
     */
    public static CellStyleModel createRightBorderColorCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , Object rightBorderColor) {
        return createBorderColorCellStyleModel(sheetName, rowIndex, columnIndex, null, rightBorderColor, null, null);
    }
 
    /**
     * 生成下边框线条颜色样式信息
     *
     * @param sheetName         sheet页名称
     * @param rowIndex          行号
     * @param columnIndex       列号
     * @param bottomBorderColor 下边框线条颜色
     * @return
     */
    public static CellStyleModel createBottomBorderColorCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , Object bottomBorderColor) {
        return createBorderColorCellStyleModel(sheetName, rowIndex, columnIndex, null, null, bottomBorderColor, null);
    }
 
    /**
     * 生成左边框线条颜色样式信息
     *
     * @param sheetName       sheet页名称
     * @param rowIndex        行号
     * @param columnIndex     列号
     * @param leftBorderColor 左边框线条颜色
     * @return
     */
    public static CellStyleModel createLeftBorderColorCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , Object leftBorderColor) {
        return createBorderColorCellStyleModel(sheetName, rowIndex, columnIndex, null, null, null, leftBorderColor);
    }
 
    /**
     * 生成上边框线条类型样式信息
     *
     * @param sheetName   sheet页名称
     * @param rowIndex    行号
     * @param columnIndex 列号
     * @param borderTop   上边框线条类型
     * @return
     */
    public static CellStyleModel createTopBorderLineTypeCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , BorderStyle borderTop) {
        return createBorderLineTypeCellStyleModel(sheetName, rowIndex, columnIndex, borderTop, null, null, null);
    }
 
    /**
     * 生成右边框线条类型样式信息
     *
     * @param sheetName   sheet页名称
     * @param rowIndex    行号
     * @param columnIndex 列号
     * @param borderRight 右边框线条类型
     * @return
     */
    public static CellStyleModel createRightBorderLineTypeCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , BorderStyle borderRight) {
        return createBorderLineTypeCellStyleModel(sheetName, rowIndex, columnIndex, null, borderRight, null, null);
    }
 
    /**
     * 生成下边框线条类型样式信息
     *
     * @param sheetName    sheet页名称
     * @param rowIndex     行号
     * @param columnIndex  列号
     * @param borderBottom 下边框线条类型
     * @return
     */
    public static CellStyleModel createBottomBorderLineTypeCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , BorderStyle borderBottom) {
        return createBorderLineTypeCellStyleModel(sheetName, rowIndex, columnIndex, null, null, borderBottom, null);
    }
 
    /**
     * 生成左边框线条类型样式信息
     *
     * @param sheetName   sheet页名称
     * @param rowIndex    行号
     * @param columnIndex 列号
     * @param borderLeft  左边框线条类型
     * @return
     */
    public static CellStyleModel createLeftBorderLineTypeCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , BorderStyle borderLeft) {
        return createBorderLineTypeCellStyleModel(sheetName, rowIndex, columnIndex, null, null, null, borderLeft);
    }
 
    /**
     * 生成边框线条颜色样式信息
     *
     * @param sheetName   sheet页名称
     * @param rowIndex    行号
     * @param columnIndex 列号
     * @param borderColor 边框线条颜色
     * @return
     */
    public static CellStyleModel createBorderColorCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , Object borderColor) {
        return createBorderCellStyleModel(sheetName, rowIndex, columnIndex, null, borderColor);
    }
 
    /**
     * 生成边框线条颜色样式信息
     *
     * @param sheetName         sheet页名称
     * @param rowIndex          行号
     * @param columnIndex       列号
     * @param topBorderColor    上边框线条颜色
     * @param rightBorderColor  右边框线条颜色
     * @param bottomBorderColor 下边框线条颜色
     * @param leftBorderColor   左边框线条颜色
     * @return
     */
    public static CellStyleModel createBorderColorCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , Object topBorderColor, Object rightBorderColor, Object bottomBorderColor, Object leftBorderColor) {
        return createBorderCellStyleModel(sheetName, rowIndex, columnIndex, null, null, null, null
                , topBorderColor, rightBorderColor, bottomBorderColor, leftBorderColor);
    }
 
    /**
     * 生成边框线条类型样式信息
     *
     * @param sheetName      sheet页名称
     * @param rowIndex       行号
     * @param columnIndex    列号
     * @param borderLineType 边框线条类型
     * @return
     */
    public static CellStyleModel createBorderLineTypeCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , BorderStyle borderLineType) {
        return createBorderCellStyleModel(sheetName, rowIndex, columnIndex, borderLineType, null);
    }
 
    /**
     * 生成边框线条类型样式信息
     *
     * @param sheetName    sheet页名称
     * @param rowIndex     行号
     * @param columnIndex  列号
     * @param borderTop    上边框线条类型
     * @param borderRight  右边框线条类型
     * @param borderBottom 下边框线条类型
     * @param borderLeft   左边框线条类型
     * @return
     */
    public static CellStyleModel createBorderLineTypeCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , BorderStyle borderTop, BorderStyle borderRight, BorderStyle borderBottom, BorderStyle borderLeft) {
        return createBorderCellStyleModel(sheetName, rowIndex, columnIndex, borderTop, borderRight, borderBottom, borderLeft
                , null, null, null, null);
    }
 
    /**
     * 生成边框样式信息
     *
     * @param sheetName      sheet页名称
     * @param rowIndex       行号
     * @param columnIndex    列号
     * @param borderLineType 边框线条类型
     * @param borderColor    边框线条颜色
     * @return
     */
    public static CellStyleModel createBorderCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , BorderStyle borderLineType, Object borderColor) {
        return createBorderCellStyleModel(sheetName, rowIndex, columnIndex, borderLineType, borderLineType, borderLineType, borderLineType
                , borderColor, borderColor, borderColor, borderColor);
    }
 
    /**
     * 生成边框样式信息
     *
     * @param sheetName         sheet页名称
     * @param rowIndex          行号
     * @param columnIndex       列号
     * @param borderTop         上边框线条类型
     * @param borderRight       右边框线条类型
     * @param borderBottom      下边框线条类型
     * @param borderLeft        左边框线条类型
     * @param topBorderColor    上边框线条颜色
     * @param rightBorderColor  右边框线条颜色
     * @param bottomBorderColor 下边框线条颜色
     * @param leftBorderColor   左边框线条颜色
     * @return
     */
    public static CellStyleModel createBorderCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , BorderStyle borderTop, BorderStyle borderRight, BorderStyle borderBottom, BorderStyle borderLeft, Object topBorderColor
            , Object rightBorderColor, Object bottomBorderColor, Object leftBorderColor) {
        return createCellStyleModel(sheetName, rowIndex, columnIndex, null, null, null, null, null, null, null, null
                , null, borderTop, borderRight, borderBottom, borderLeft, topBorderColor, rightBorderColor
                , bottomBorderColor, leftBorderColor);
    }
 
    /**
     * 生成样式信息
     *
     * @param sheetName         sheet页名称
     * @param rowIndex          行号
     * @param columnIndex       列号
     * @param fontName          字体名称(宋体)
     * @param fontHeight        字体大小
     * @param fontColor         字体颜色
     * @param fontBold          字体加粗
     * @param fontItalic        字体斜体
     * @param fontUnderLine     字体下划线
     * @param fontTypeOffset    字体上标下标
     * @param fontStrikeout     字体删除线
     * @param backgroundColor   背景颜色
     * @param borderTop         上边框线条类型
     * @param borderRight       右边框线条类型
     * @param borderBottom      下边框线条类型
     * @param borderLeft        左边框线条类型
     * @param topBorderColor    上边框线条颜色
     * @param rightBorderColor  右边框线条颜色
     * @param bottomBorderColor 下边框线条颜色
     * @param leftBorderColor   左边框线条颜色
     * @return
     */
    public static CellStyleModel createCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , String fontName, Double fontHeight, Object fontColor, Boolean fontBold, Boolean fontItalic, Byte fontUnderLine
            , Short fontTypeOffset, Boolean fontStrikeout, Object backgroundColor, BorderStyle borderTop, BorderStyle borderRight
            , BorderStyle borderBottom, BorderStyle borderLeft, Object topBorderColor, Object rightBorderColor, Object bottomBorderColor
            , Object leftBorderColor) {
        return createCellStyleModel(sheetName, rowIndex, columnIndex, fontName, fontHeight, fontColor, fontBold, fontItalic
                , fontUnderLine, fontTypeOffset, fontStrikeout, backgroundColor, borderTop, borderRight, borderBottom
                , borderLeft, topBorderColor, rightBorderColor, bottomBorderColor, leftBorderColor, null, null);
    }
 
    /**
     * 生成水平对齐方式信息
     *
     * @param sheetName           sheet页名称
     * @param rowIndex            行号
     * @param columnIndex         列号
     * @param horizontalAlignment 水平对齐方式
     * @return
     */
    public static CellStyleModel createHorizontalAlignmentCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , HorizontalAlignment horizontalAlignment) {
        return createAlignmentCellStyleModel(sheetName, rowIndex, columnIndex, horizontalAlignment, null);
    }
 
    /**
     * 生成垂直对齐方式信息
     *
     * @param sheetName         sheet页名称
     * @param rowIndex          行号
     * @param columnIndex       列号
     * @param verticalAlignment 垂直对齐方式
     * @return
     */
    public static CellStyleModel createVerticalAlignmentCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , VerticalAlignment verticalAlignment) {
        return createAlignmentCellStyleModel(sheetName, rowIndex, columnIndex, null, verticalAlignment);
    }
 
    /**
     * 生成对齐方式信息
     *
     * @param sheetName           sheet页名称
     * @param rowIndex            行号
     * @param columnIndex         列号
     * @param horizontalAlignment 水平对齐方式
     * @param verticalAlignment   垂直对齐方式
     * @return
     */
    public static CellStyleModel createAlignmentCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment) {
        return createCellStyleModel(sheetName, rowIndex, columnIndex, null, null, null, null
                , null, null, null, null, null, null, null
                , null, null, null, null, null, null
                , horizontalAlignment, verticalAlignment);
    }
 
    /**
     * 生成样式信息
     *
     * @param sheetName           sheet页名称
     * @param rowIndex            行号
     * @param columnIndex         列号
     * @param fontName            字体名称(宋体)
     * @param fontHeight          字体大小
     * @param fontColor           字体颜色
     * @param fontBold            字体加粗
     * @param fontItalic          字体斜体
     * @param fontUnderLine       字体下划线
     * @param fontTypeOffset      字体上标下标
     * @param fontStrikeout       字体删除线
     * @param backgroundColor     背景颜色
     * @param borderTop           上边框线条类型
     * @param borderRight         右边框线条类型
     * @param borderBottom        下边框线条类型
     * @param borderLeft          左边框线条类型
     * @param topBorderColor      上边框线条颜色
     * @param rightBorderColor    右边框线条颜色
     * @param bottomBorderColor   下边框线条颜色
     * @param leftBorderColor     左边框线条颜色
     * @param horizontalAlignment 水平对齐方式
     * @param verticalAlignment   垂直对齐方式
     * @return
     */
    public static CellStyleModel createCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , String fontName, Double fontHeight, Object fontColor, Boolean fontBold, Boolean fontItalic, Byte fontUnderLine
            , Short fontTypeOffset, Boolean fontStrikeout, Object backgroundColor, BorderStyle borderTop, BorderStyle borderRight
            , BorderStyle borderBottom, BorderStyle borderLeft, Object topBorderColor, Object rightBorderColor, Object bottomBorderColor
            , Object leftBorderColor, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment) {
        return createCellStyleModel(sheetName, rowIndex, columnIndex, fontName, fontHeight, fontColor, fontBold, fontItalic
                , fontUnderLine, fontTypeOffset, fontStrikeout, backgroundColor, borderTop, borderRight, borderBottom
                , borderLeft, topBorderColor, rightBorderColor, bottomBorderColor, leftBorderColor, horizontalAlignment, verticalAlignment, null);
    }
 
    /**
     * 生成自动换行样式信息
     *
     * @param sheetName   sheet页名称
     * @param rowIndex    行号
     * @param columnIndex 列号
     * @param wrapText    自动换行
     * @return
     */
    public static CellStyleModel createWrapTextCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , Boolean wrapText) {
        return createCellStyleModel(sheetName, rowIndex, columnIndex, null, null, null, null, null
                , null, null, null, null, null, null, null
                , null, null, null, null, null, null, null
                , wrapText);
    }
 
    /**
     * 生成样式信息
     *
     * @param sheetName           sheet页名称
     * @param rowIndex            行号
     * @param columnIndex         列号
     * @param fontName            字体名称(宋体)
     * @param fontHeight          字体大小
     * @param fontColor           字体颜色
     * @param fontBold            字体加粗
     * @param fontItalic          字体斜体
     * @param fontUnderLine       字体下划线
     * @param fontTypeOffset      字体上标下标
     * @param fontStrikeout       字体删除线
     * @param backgroundColor     背景颜色
     * @param borderTop           上边框线条类型
     * @param borderRight         右边框线条类型
     * @param borderBottom        下边框线条类型
     * @param borderLeft          左边框线条类型
     * @param topBorderColor      上边框线条颜色
     * @param rightBorderColor    右边框线条颜色
     * @param bottomBorderColor   下边框线条颜色
     * @param leftBorderColor     左边框线条颜色
     * @param horizontalAlignment 水平对齐方式
     * @param verticalAlignment   垂直对齐方式
     * @param wrapText            自动换行
     * @return
     */
    public static CellStyleModel createCellStyleModel(String sheetName, int rowIndex, int columnIndex
            , String fontName, Double fontHeight, Object fontColor, Boolean fontBold, Boolean fontItalic, Byte fontUnderLine
            , Short fontTypeOffset, Boolean fontStrikeout, Object backgroundColor, BorderStyle borderTop, BorderStyle borderRight
            , BorderStyle borderBottom, BorderStyle borderLeft, Object topBorderColor, Object rightBorderColor, Object bottomBorderColor
            , Object leftBorderColor, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment, Boolean wrapText) {
        CellStyleModel cellStyleModel = new CellStyleModel();
        //sheet页名称
        cellStyleModel.setSheetName(sheetName);
        //行号
        cellStyleModel.setRowIndex(rowIndex);
        //列号
        cellStyleModel.setColIndex(columnIndex);
 
        //设置字体样式
        //字体名称(比如宋体)
        fontName = fontName != null && StrUtil.equals(fontName, "") ? "宋体" : fontName;
        cellStyleModel.setFontName(fontName);
        //字体大小
        fontHeight = fontHeight != null && fontHeight <= 0 ? null : fontHeight;
        cellStyleModel.setFontHeight(fontHeight);
        //字体颜色
        fontColor = fontColor != null && (fontColor instanceof IndexedColors == false && fontColor instanceof XSSFColor == false)
                ? null : fontColor;
        cellStyleModel.setFontColor(fontColor);
        //字体加粗
        cellStyleModel.setFontBold(fontBold);
        //字体斜体
        cellStyleModel.setFontItalic(fontItalic);
        //字体下划线
        fontUnderLine = fontUnderLine != null && (fontUnderLine != Font.U_NONE && fontUnderLine != Font.U_SINGLE && fontUnderLine != Font.U_DOUBLE
                && fontUnderLine != Font.U_DOUBLE_ACCOUNTING && fontUnderLine != Font.U_SINGLE_ACCOUNTING) ? null : fontUnderLine;
        cellStyleModel.setFontUnderLine(fontUnderLine);
        //字体上标下标
        fontTypeOffset = fontTypeOffset != null && (fontTypeOffset != Font.SS_NONE && fontTypeOffset != Font.SS_SUB && fontTypeOffset != Font.SS_SUPER)
                ? null : fontTypeOffset;
        cellStyleModel.setFontTypeOffset(fontTypeOffset);
        //字体删除线
        cellStyleModel.setFontStrikeout(fontStrikeout);
 
        //背景颜色
        backgroundColor = backgroundColor != null && (backgroundColor instanceof IndexedColors == false && backgroundColor instanceof XSSFColor == false)
                ? null : backgroundColor;
        cellStyleModel.setBackgroundColor(backgroundColor);
 
        //边框样式
        //上边框线条类型
        cellStyleModel.setBorderTop(borderTop);
        //右边框线条类型
        cellStyleModel.setBorderRight(borderRight);
        //下边框线条类型
        cellStyleModel.setBorderBottom(borderBottom);
        //左边框线条类型
        cellStyleModel.setBorderLeft(borderLeft);
        //上边框颜色类型
        cellStyleModel.setTopBorderColor(topBorderColor);
        //右边框颜色类型
        cellStyleModel.setRightBorderColor(rightBorderColor);
        //下边框颜色类型
        cellStyleModel.setBottomBorderColor(bottomBorderColor);
        //左边框颜色类型
        cellStyleModel.setLeftBorderColor(leftBorderColor);
 
        //对齐方式
        //水平对齐方式
        cellStyleModel.setHorizontalAlignment(horizontalAlignment);
        //垂直对齐方式
        cellStyleModel.setVerticalAlignment(verticalAlignment);
 
        //自动换行
        cellStyleModel.setWrapText(wrapText);
        return cellStyleModel;
    }
}

3、 CustomCellStyleHandler
自定义单元格样式处理器,可支持字体样式、背景颜色、边框样式、对齐方式、自动换行。

package com.easyexcel;
 
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.write.handler.AbstractRowWriteHandler;
import com.alibaba.excel.write.metadata.holder.*;
import com.easyexcel.model.CellStyleModel;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
 
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 自定义单元格样式处理器(支持字体样式、背景颜色、边框样式、对齐方式、自动换行)
 */
public class CustomCellStyleHandler extends AbstractRowWriteHandler {
    /**
     * sheet页名称列表
     */
    private List<String> sheetNameList;
    /**
     * 样式信息
     */
    private List<CellStyleModel> cellStyleList = new ArrayList<>();
 
    /**
     * 自定义样式适配器构造方法
     *
     * @param cellStyleList 样式信息
     */
    public CustomCellStyleHandler(List<CellStyleModel> cellStyleList) {
        if (CollectionUtil.isEmpty(cellStyleList)) {
            return;
        }
        cellStyleList = cellStyleList.stream().filter(x -> x != null
                //判断sheet名称KEY是否存在
                && StrUtil.isNotBlank(x.getSheetName())
                //字体样式
                //判断字体颜色KEY是否存在
                && (x.getFontColor() == null || x.getFontColor() instanceof IndexedColors
                || x.getFontColor() instanceof XSSFColor)
                //判断背景颜色KEY是否存在
                && (x.getBackgroundColor() == null || x.getBackgroundColor() instanceof IndexedColors
                || x.getBackgroundColor() instanceof XSSFColor)
                //边框样式
                // 判断上边框线条颜色KEY是否存在
                && (x.getTopBorderColor() == null || x.getTopBorderColor() instanceof IndexedColors
                || x.getTopBorderColor() instanceof XSSFColor)
                // 判断右边框线条颜色KEY是否存在
                && (x.getRightBorderColor() == null || x.getRightBorderColor() instanceof IndexedColors
                || x.getRightBorderColor() instanceof XSSFColor)
                // 判断下边框线条颜色KEY是否存在
                && (x.getBottomBorderColor() == null || x.getBottomBorderColor() instanceof IndexedColors
                || x.getBottomBorderColor() instanceof XSSFColor)
                // 判断左边框线条颜色KEY是否存在
                && (x.getLeftBorderColor() == null || x.getLeftBorderColor() instanceof IndexedColors
                || x.getLeftBorderColor() instanceof XSSFColor)
        ).collect(Collectors.toList());
        this.cellStyleList = cellStyleList;
        sheetNameList = this.cellStyleList.stream().map(x -> x.getSheetName()).distinct().collect(Collectors.toList());
    }
 
    @Override
    public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row
            , Integer relativeRowIndex, Boolean isHead) {
        Sheet sheet = writeSheetHolder.getSheet();
        //不需要添加样式,或者当前sheet页不需要添加样式
        if (cellStyleList == null || cellStyleList.size() <= 0 || sheetNameList.contains(sheet.getSheetName()) == false) {
            return;
        }
        //获取当前行的样式信息
        List<CellStyleModel> rowCellStyleList = cellStyleList.stream().filter(x ->
                StrUtil.equals(x.getSheetName(), sheet.getSheetName()) && x.getRowIndex() == relativeRowIndex).collect(Collectors.toList());
        //该行不需要设置样式
        if (rowCellStyleList == null || rowCellStyleList.size() <= 0) {
            return;
        }
        for (CellStyleModel cellStyleModel : rowCellStyleList) {
            //设置单元格样式
            setCellStyle(cellStyleModel, row);
        }
        //删除已添加的样式信息
        cellStyleList.removeAll(rowCellStyleList);
        //重新获取要添加的sheet页姓名
        sheetNameList = cellStyleList.stream().map(x -> x.getSheetName()).distinct().collect(Collectors.toList());
    }
 
    /**
     * 给单元格设置样式
     *
     * @param cellStyleModel 样式信息
     * @param row            行对象
     */
    private void setCellStyle(CellStyleModel cellStyleModel, Row row) {
        //背景颜色
        Object backgroundColor = cellStyleModel.getBackgroundColor();
        //自动换行
        Boolean wrapText = cellStyleModel.getWrapText();
        //列索引
        int colIndex = cellStyleModel.getColIndex();
        //边框样式
        Cell cell = row.getCell(colIndex);
        if (cell == null) {
            cell = row.createCell(colIndex);
        }
        XSSFCellStyle style = (XSSFCellStyle) cell.getRow().getSheet().getWorkbook().createCellStyle();
        // 克隆出一个 style
        style.cloneStyleFrom(cell.getCellStyle());
        //设置背景颜色
        if (backgroundColor != null) {
            //使用IndexedColors定义的颜色
            if (backgroundColor instanceof IndexedColors) {
                style.setFillForegroundColor(((IndexedColors) backgroundColor).getIndex());
            }
            //使用自定义的RGB颜色
            else if (backgroundColor instanceof XSSFColor) {
                style.setFillForegroundColor((XSSFColor) backgroundColor);
            }
            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        }
        //设置自动换行
        if (wrapText != null) {
            style.setWrapText(wrapText);
        }
        //设置字体样式
        setFontStyle(row, style, cellStyleModel);
        //设置边框样式
        setBorderStyle(style, cellStyleModel);
        //设置对齐方式
        setAlignmentStyle(style, cellStyleModel);
        cell.setCellStyle(style);
    }
 
    /**
     * 设置字体样式
     *
     * @param row            行对象
     * @param style          单元格样式
     * @param cellStyleModel 样式信息
     */
    private void setFontStyle(Row row, XSSFCellStyle style, CellStyleModel cellStyleModel) {
        //字体名称
        String fontName = cellStyleModel.getFontName();
        //字体大小
        Double fontHeight = cellStyleModel.getFontHeight();
        //字体颜色
        Object fontColor = cellStyleModel.getFontColor();
        //字体加粗
        Boolean fontBold = cellStyleModel.getFontBold();
        //字体斜体
        Boolean fontItalic = cellStyleModel.getFontItalic();
        //字体下划线
        Byte fontUnderLine = cellStyleModel.getFontUnderLine();
        //字体上标下标
        Short fontTypeOffset = cellStyleModel.getFontTypeOffset();
        //字体删除线
        Boolean fontStrikeout = cellStyleModel.getFontStrikeout();
        //不需要设置字体样式
        if (fontName == null && fontHeight == null && fontColor == null && fontBold == null && fontItalic == null
                && fontUnderLine == null && fontTypeOffset == null && fontStrikeout == null) {
            return;
        }
        XSSFFont font = null;
        //样式存在字体对象时,使用原有的字体对象
        if (style.getFontIndex() != 0) {
            font = style.getFont();
        }
        //样式不存在字体对象时,创建字体对象
        else {
            font = (XSSFFont) row.getSheet().getWorkbook().createFont();
            //默认字体为宋体
            font.setFontName("宋体");
        }
        //设置字体名称
        if (fontName != null) {
            font.setFontName(fontName);
        }
        //设置字体大小
        if (fontHeight != null) {
            font.setFontHeight(fontHeight);
        }
        //设置字体颜色
        if (fontColor != null) {
            //使用IndexedColors定义的颜色
            if (fontColor instanceof IndexedColors) {
                font.setColor(((IndexedColors) fontColor).getIndex());
            }
            //使用自定义的RGB颜色
            else if (fontColor instanceof XSSFColor) {
                font.setColor((XSSFColor) fontColor);
            }
        }
        //设置字体加粗
        if (fontBold != null) {
            font.setBold(fontBold);
        }
        //设置字体斜体
        if (fontItalic != null) {
            font.setItalic(fontItalic);
        }
        //设置字体下划线
        if (fontUnderLine != null) {
            font.setUnderline(fontUnderLine);
        }
        //设置字体上标下标
        if (fontTypeOffset != null) {
            font.setTypeOffset(fontTypeOffset);
        }
        //设置字体删除线
        if (fontStrikeout != null) {
            font.setStrikeout(fontStrikeout);
        }
        style.setFont(font);
    }
 
    /**
     * 设置边框样式
     *
     * @param style          单元格样式
     * @param cellStyleModel 样式信息
     */
    private void setBorderStyle(XSSFCellStyle style, CellStyleModel cellStyleModel) {
        //上边框线条类型
        BorderStyle borderTop = cellStyleModel.getBorderTop();
        //右边框线条类型
        BorderStyle borderRight = cellStyleModel.getBorderRight();
        //下边框线条类型
        BorderStyle borderBottom = cellStyleModel.getBorderBottom();
        //左边框线条类型
        BorderStyle borderLeft = cellStyleModel.getBorderLeft();
        //上边框颜色类型
        Object topBorderColor = cellStyleModel.getTopBorderColor();
        //右边框颜色类型
        Object rightBorderColor = cellStyleModel.getRightBorderColor();
        //下边框颜色类型
        Object bottomBorderColor = cellStyleModel.getBottomBorderColor();
        //左边框颜色类型
        Object leftBorderColor = cellStyleModel.getLeftBorderColor();
        //不需要设置边框样式
        if (borderTop == null && borderRight == null && borderBottom == null && borderLeft == null && topBorderColor == null
                && rightBorderColor == null && bottomBorderColor == null && leftBorderColor == null) {
            return;
        }
        //设置上边框线条类型
        if (borderTop != null) {
            style.setBorderTop(borderTop);
        }
        //设置右边框线条类型
        if (borderRight != null) {
            style.setBorderRight(borderRight);
        }
        //设置下边框线条类型
        if (borderBottom != null) {
            style.setBorderBottom(borderBottom);
        }
        //设置左边框线条类型
        if (borderLeft != null) {
            style.setBorderLeft(borderLeft);
        }
        //设置上边框线条颜色
        if (topBorderColor != null) {
            //使用IndexedColors定义的颜色
            if (topBorderColor instanceof IndexedColors) {
                style.setTopBorderColor(((IndexedColors) topBorderColor).getIndex());
            }
            //使用自定义的RGB颜色
            else if (topBorderColor instanceof XSSFColor) {
                style.setTopBorderColor((XSSFColor) topBorderColor);
            }
        }
        //设置右边框线条颜色
        if (rightBorderColor != null) {
            //使用IndexedColors定义的颜色
            if (rightBorderColor instanceof IndexedColors) {
                style.setRightBorderColor(((IndexedColors) rightBorderColor).getIndex());
            }
            //使用自定义的RGB颜色
            else if (rightBorderColor instanceof XSSFColor) {
                style.setRightBorderColor((XSSFColor) rightBorderColor);
            }
        }
        //设置下边框线条颜色
        if (bottomBorderColor != null) {
            //使用IndexedColors定义的颜色
            if (bottomBorderColor instanceof IndexedColors) {
                style.setBottomBorderColor(((IndexedColors) bottomBorderColor).getIndex());
            }
            //使用自定义的RGB颜色
            else if (bottomBorderColor instanceof XSSFColor) {
                style.setBottomBorderColor((XSSFColor) bottomBorderColor);
            }
        }
        //设置左边框线条颜色
        if (leftBorderColor != null) {
            //使用IndexedColors定义的颜色
            if (leftBorderColor instanceof IndexedColors) {
                style.setLeftBorderColor(((IndexedColors) leftBorderColor).getIndex());
            }
            //使用自定义的RGB颜色
            else if (topBorderColor instanceof XSSFColor) {
                style.setLeftBorderColor((XSSFColor) leftBorderColor);
            }
        }
    }
 
    /**
     * 设置对齐方式
     *
     * @param style          单元格样式
     * @param cellStyleModel 样式信息
     */
    private void setAlignmentStyle(XSSFCellStyle style, CellStyleModel cellStyleModel) {
        //水平对齐方式
        HorizontalAlignment horizontalAlignment = cellStyleModel.getHorizontalAlignment();
        //垂直对齐方式
        VerticalAlignment verticalAlignment = cellStyleModel.getVerticalAlignment();
        //不需要设置对齐方式
        if (horizontalAlignment == null && verticalAlignment == null) {
            return;
        }
        //设置水平对齐方式
        if (horizontalAlignment != null) {
            style.setAlignment(horizontalAlignment);
        }
        //设置垂直对齐方式
        if (verticalAlignment != null) {
            style.setVerticalAlignment(verticalAlignment);
        }
    }
}

4、 调试代码

   /**
     * 导出(设置单元格样式,支持字体样式、背景颜色、边框样式、对齐方式、自动换行)
     *
     * @param response
     */
    @GetMapping("/exportCellStyle")
    public void exportCellStyle(HttpServletResponse response) {
        try {
            //生成表格数据
            List<List<Object>> dataList = new ArrayList<>();
            dataList.add(new ArrayList<>(Arrays.asList(new Object[]{"表头11", "表头2", "表头3", "表头4"})));
            dataList.add(new ArrayList<>(Arrays.asList(new Object[]{"表头17777777777", "表头2", "表头3", "表头4444"})));
            dataList.add(new ArrayList<>(Arrays.asList(new Object[]{"表头31", "表头2", "表头3", "表头4"})));
            //导出文件
            String fileName = new String("文件名称.xlsx".getBytes(), "UTF-8");
 
            List<CellStyleModel> cellStyleList = new ArrayList<>();
            //设置单元格字体(黑体),单元格大小 18号,字体颜色红色,加粗,斜体,下划线,上标,删除线
            cellStyleList.add(CellStyleModel.createFontCellStyleModel("模板", 0, 0, "黑体", 18D, IndexedColors.RED
                    , true, true, Font.U_SINGLE, Font.SS_SUPER, true));
            //设置单元格背景颜色
            cellStyleList.add(CellStyleModel.createBackgroundColorCellStyleModel("模板", 0, 1, IndexedColors.BLUE));
            //设置单元格边框类型和边框颜色
            cellStyleList.add(CellStyleModel.createBorderCellStyleModel("模板", 0, 2, BorderStyle.DOUBLE, IndexedColors.RED));
            //设置对齐方式
            cellStyleList.add(CellStyleModel.createAlignmentCellStyleModel("模板", 0, 3, HorizontalAlignment.RIGHT, VerticalAlignment.BOTTOM));
            //设置自动换行
            cellStyleList.add(CellStyleModel.createWrapTextCellStyleModel("模板", 1, 0, true));
            response.addHeader("Content-Disposition", "filename=" + fileName);
            //设置类型,扩展名为.xls
            response.setContentType("application/vnd.ms-excel");
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerWriteHandler(new CustomCellStyleHandler(cellStyleList)).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();
            excelWriter.write(dataList, writeSheet);
            //千万别忘记finish 会帮忙关闭流
            excelWriter.finish();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

5、调试结果
在这里插入图片描述

  • 8
    点赞
  • 76
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值