Monday, 24 February 2020 07:45

Alternate Row Colors in Excel in Java

Written by  support iceblue
Rate this item
(0 votes)

This article demonstrates how to set alternate colors for Excel rows through conditional formatting using Spire.XLS for Java.

import com.spire.xls.*;

import java.awt.*;

public class ConditionalFormatting {

    public static void main(String[] args) {

        //Create a Workbook object
        Workbook workbook = new Workbook();

        //Load a sample document
        workbook.loadFromFile("C:\\Users\\Jack\\Desktop\\Example.xlsx");

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

        //Get the data range
        CellRange dataRange = sheet.getAllocatedRange();

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

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

        //Save the document
        workbook.saveToFile("output/AlternateColor.xlsx", ExcelVersion.Version2016);
    }
}

Alternate Row Colors in Excel in Java

Additional Info

  • tutorial_title: