Add Traffic Lights Icons to Excel in Java
The traffic light icon in Excel is a conditional formatting mainly used to manage the progress and status of a project. In this article, you will learn how to programmatically add the traffic lights icons in Excel by using a free library--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
import com.spire.xls.*;
import com.spire.xls.core.IConditionalFormat;
import com.spire.xls.core.spreadsheet.collections.XlsConditionalFormats;
import java.awt.*;
public class setTrafficLightsIcons {
public static void main(String[] args) {
//Create a workbook
Workbook workbook = new Workbook();
//Add a worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Add data to cells
sheet.getCellRange("A1").setText("Project Progress");
sheet.getCellRange("A2").setNumberValue(0.95);
sheet.getCellRange("A3").setNumberValue(0.5);
sheet.getCellRange("A4").setNumberValue(0.1);
sheet.getCellRange("A5").setNumberValue(0.9);
sheet.getCellRange("A6").setNumberValue(0.7);
sheet.getCellRange("A7").setNumberValue(0.6);
//set number format for the cell range
sheet.getCellRange("A2:A7").setNumberFormat("0%");
//Set row height and column width for the cell range
sheet.getAllocatedRange().setRowHeight(20);
sheet.getAllocatedRange().setColumnWidth(25);
//Add a conditional formatting
XlsConditionalFormats conditional = sheet.getConditionalFormats().add();
conditional.addRange(sheet.getAllocatedRange());
IConditionalFormat format1 = conditional.addCondition();
//Set the conditional format type, formula, comparison operator type and color
format1.setFormatType(ConditionalFormatType.CellValue);
format1.setFirstFormula("300");
format1.setOperator(ComparisonOperatorType.Less);
format1.setFontColor(Color.black);
format1.setBackColor(Color.lightGray);
//Add a conditional formatting of traffic lights icon to the cell range
conditional.addRange(sheet.getAllocatedRange());
IConditionalFormat format = conditional.addCondition();
format.setFormatType(ConditionalFormatType.IconSet);
format.getIconSet().setIconSetType(IconSetType.ThreeTrafficLights1);
//Save to file
workbook.saveToFile( "output/setTrafficLightsIcons.xlsx", ExcelVersion.Version2013);
}
}