Change Fill Color and Pattern of Cells in Excel in Java

Change Fill Color and Pattern of Cells in Excel in Java

·

2 min read

When creating a large Excel document, you can add emphasis to the selected cells by changing the fill color or applying a pattern to the cells. By doing this, you can also make your data easier to understand visually. This article will introduce how to programmatically change the background color and pattern of a specified cell or cell range in Excel using Free Spire.XLS for Java.

Import Jar Dependency (2 Method)

1# Download the free library and unzip it, then add the Spire.Xls.jar file to your project as dependency.
2# Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>http://repo.e iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.xls.free</artifactId>
        <version>5.1.0</version>
    </dependency>
</dependencies>

Sample Code

Free Spire.XLS for Java offers the Worksheet.getRange().get() method to get a specified cell or cell range, and then you can use the CellRange.getStyle().setColor() method and CellRange.getStyle().setFillPattern() method to set fill color and fill pattern style for the specified cell or cell range. The complete sample code is shown as below:

import com.spire.xls.*;
import java.awt.*;

public class CellBackground {
    public static void main(String[] args) {
        //Create a Workbook object
        Workbook workbook = new Workbook();

        //Load a sample Excel document
        workbook.loadFromFile("test.xlsx");

        //Get the first worksheet
        Worksheet worksheet= workbook.getWorksheets().get(0);

        //Set background color for cell ranges
        worksheet.getRange().get("A1:D1").getStyle().setColor(Color.green);
        worksheet.getRange().get("A4:A7").getStyle().setColor(Color.pink);

        //Set background color for cell E8
        worksheet.getRange().get("C9").getStyle().setColor(Color.red);

        //Set fill pattern style for a cell range
        worksheet.getRange().get("C3:D4").getStyle().setFillPattern(ExcelPatternType.Percent25Gray);

        //Save the document
        workbook.saveToFile("CellBackground.xlsx", ExcelVersion.Version2013);
    }
}

FillCell.jpg