Contents

Apache POI 设置单元的背景颜色

1.概述

在 Excel 工作表上,当我们通过更改表头的背景颜色来突出显示表头时,它总是看起来很优雅。本文介绍如何使用Apache POI 更改单元格背景颜色。

此外,我们建议阅读我们在 Java 中使用 Microsoft Excel 教程,以了解在 Java 中使用 Excel 的一些基础知识。

2. Maven依赖

首先,我们需要在pom.xml中添加poi-ooxml作为依赖项:

<dependency>
     <groupId>org.apache.poi</groupId>
     <artifactId>poi-ooxml</artifactId>
     <version>5.2.0</version>
 </dependency>

3.更改单元格背景颜色

3.1. 关于单元格背景

在 Excel 工作表上,我们可以通过填充颜色或图案来更改单元格背景。在下图中,单元格A1填充有浅蓝色背景,而单元格B1填充有图案。此图案有黑色背景和顶部的浅蓝色斑点:

/uploads/apache_poi_background_color/1.png

3.2. 更改背景颜色的代码

Apache POI 提供了三种更改背景颜色的方法。在CellStyle类中,我们可以为此目的使用setFillForegroundColorsetFillPatternsetFillBackgroundColor方法。**在IndexedColors类中定义了一个颜色列表。同样,在FillPatternType中定义了一个模式列表。

有时,名称setFillBackgroundColor可能会误导我们。但是,该方法本身不足以改变单元格背景。要通过填充纯色来更改单元格背景,我们使用setFillForegroundColorsetFillPattern方法。第一种方法告诉要填充什么颜色,而第二种方法指定要使用的纯色填充图案。

以下代码段是更改单元格背景的示例方法,如单元格A1所示:

public void changeCellBackgroundColor(Cell cell) {
    CellStyle cellStyle = cell.getCellStyle();
    if(cellStyle == null) {
        cellStyle = cell.getSheet().getWorkbook().createCellStyle();
    }
    cellStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
    cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    cell.setCellStyle(cellStyle);
}

要使用图案更改单元格背景,我们需要使用两种颜色:一种颜色填充整个背景,另一种颜色在第一种颜色之上填充图案。在这里,我们需要使用所有这三种方法。

这里使用方法setFillBackgroundColor来指定背景颜色。仅使用此方法不会产生任何效果。我们需要使用setFillForegroundColor选择第二种颜色并使用setFillPattern来说明图案类型。

以下代码段是更改单元格背景的示例方法,如单元格B1所示:

public void changeCellBackgroundColorWithPattern(Cell cell) {
    CellStyle cellStyle = cell.getCellStyle();
    if(cellStyle == null) {
        cellStyle = cell.getSheet().getWorkbook().createCellStyle();
    }
    cellStyle.setFillBackgroundColor(IndexedColors.BLACK.index);
    cellStyle.setFillPattern(FillPatternType.BIG_SPOTS);
    cellStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
    cell.setCellStyle(cellStyle);
}