Java sets alternate background colors for rows in Excel

Posted by Petran76 on Thu, 09 Apr 2020 16:14:50 +0200

When making excel tables, by filling two adjacent rows in the data table with different background colors, you can make the data in each row look clearer, avoid reading wrong rows, and increase the beauty of Excel tables. This article describes how to set alternate background colors for Excel odd and even rows in a Java program.

 

Use tools: Free Spire.XLS for Java (free version)

 

Jar file import method

Method 1:

Download the latest Free Spire.XLS for Java Package and extract it, then import the spirit.xls.jar package into your Java application from the lib folder. (after the import is successful, see the figure below)

 

 

 

Method two:

Import through Maven warehouse installation. Please refer to the link for detailed operation steps( https://www.e-iceblue.cn/licensing/install-spirepdf-for-java-from-maven-repository.html)

 

 

Java code example

 

import com.spire.xls.*;

import java.awt.*;

public class ConditionalFormatting {

    public static void main(String[] args) {

        //Establish Workbook object
        Workbook workbook = new Workbook();

        //Load one Excel File
        workbook.loadFromFile("C:\\Users\\Administrator\\IdeaProjects\\XLS\\sample.xlsx");

        //Get a worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);

        //Get area with data
        CellRange dataRange = sheet.getAllocatedRange();

        //Use conditional formatting to set the background color of even rows to light gray
        ConditionalFormatWrapper format1 = dataRange.getConditionalFormats().addCondition();
        format1.setFirstFormula("=MOD(ROW(),2)=0");
        format1.setFormatType(ConditionalFormatType.Formula);
        format1.setBackColor(Color.lightGray);

        //Use conditional formatting to set the background color of odd rows to yellow
        ConditionalFormatWrapper format2 = dataRange.getConditionalFormats().addCondition();
        format2.setFirstFormula("=MOD(ROW(),2)=1");
        format2.setFormatType(ConditionalFormatType.Formula);
        format2.setBackColor(Color.yellow);

        //Save document
        workbook.saveToFile("Alternate background color.xlsx", ExcelVersion.Version2016);
    }
}

 

Alternate background color rendering:

Topics: Java Excel Maven