Data bars are a type of conditional formatting Microsoft Excel offers for visualizing the values in Excel cells. They can help you compare the values quickly because a cell with a longer bar represents a larger value, while a cell with a shorter bar represents a smaller value. This article will introduce how to add data bars in a range of cells using Spire.XLS for Java.
Install Spire.XLS for Java
First of all, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.xls</artifactId> <version>14.11.0</version> </dependency> </dependencies>
Add Data Bars in Excel
The following are steps to add data bars in a range of Excel cells through conditional formatting:
- Create a Workbook instance.
- Load an Excel file using Workbook.loadFromFile() method.
- Get the worksheets collection using Workbook.getWorksheets() method, and then get the first worksheet using WorksheetsCollection.get() method.
- Get a specific cell range using Worksheet.getCellRange() method.
- Add a new conditional formatting to the cell range using ConditionalFormats. addCondition(), and then set the type of the new conditional formatting to DataBar using ConditionalFormatWrapper.setFormatType() method.
- Set the color of the data bar using DataBar.setBarColor() method.
- Save the document to another file using Workbook.saveToFile() method.
- Java
import com.spire.xls.*; import com.spire.xls.core.*; import java.awt.*; public class applyDataBars { public static void main(String[] args) { //Create a Workbook instance Workbook workbook = new Workbook(); //Load an Excel file workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\test.xlsx"); //Get the first worksheet. Worksheet sheet = workbook.getWorksheets().get(0); //Get the specific cell range CellRange range = sheet.getCellRange("B2:B13"); //Add the conditional formatting of data bars in the cell range IConditionalFormat format = range.getConditionalFormats().addCondition(); format.setFormatType( ConditionalFormatType.DataBar); //Set color for the data bars format.getDataBar().setBarColor( Color.GREEN); //Save to file workbook.saveToFile("ApplyDataBars.xlsx", ExcelVersion.Version2013); } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.