Programming Environment
Method 1:
Introduced manually. Download Free Spire.XLS for Java locally, unzip it, and find the Spire.Xls.jar file in the lib folder. Open the following interface in IDEA, and import the jar file in the local path into the Java program:
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.
Expand|Select|Wrap|Line Numbers
- <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.free</artifactId>
- <version>5.1.0</version>
- </dependency>
- </dependencies>
Free Spire.XLS for Java offers Worksheet.getAllocatedRange().getStyle().setColor( ) method and Worksheet.getCellRange().getStyle().setColor() method to set background color of Excel Documents. More details are listed below.
Step 1: Create a Workbook instance.
Step 2: Load a sample Excel file using Workbook.loadFromFile() method.
Step 3: Get a specific worksheet from the workbook using Workbook.getWorksheets.get(index) method.
Step 4: Using Worksheet.getAllocatedRange().getStyle().setColor( ) method to set background color for the used cell range or Worksheet.getCellRange().getStyle().setColor() method to set background color for a specified cell range in the worksheet.
Step 5: Save the result file using Workbook.saveToFile() method.
Full Code:
Java
Expand|Select|Wrap|Line Numbers
- import com.spire.xls.ExcelVersion;
- import com.spire.xls.Workbook;
- import com.spire.xls.Worksheet;
- import java.awt.*;
- public class BackgroundColor{
- public static void main(String[] args){
- //Create a Workbook instance
- Workbook workbook = new Workbook();
- //Load an Excel file
- workbook.loadFromFile("input.xlsx");
- //Get the first worksheet
- Worksheet sheet = workbook.getWorksheets().get(0);
- //Set background color for the used cell range in the worksheet
- sheet.getAllocatedRange().getStyle().setColor(Color.yellow);
- //Set background color for a specified cell range in the worksheet
- //sheet.getCellRange("A1:E19").getStyle().setColor(Color.blue);
- //Save the file
- workbook.saveToFile("SetBackColor.xlsx", ExcelVersion.Version2013);
- }
- }
Conclusion:
In this post, you have learned how to set the background color of Excel documents in Java. Not only that, we also have other functions, such as, Java: Merge Excel Files into One,Java: Apply Color to Alternate Rows in Excel Using Conditional Formatting and so on. Apart from that, if you'd like to learn more, you can visit this link to explore more about for Spire.XLS for Java.