Set Background Color and Image for Excel Using Java

·

2 min read

Usually the default background of Excel documents is white, and in order to beautify the document, we can set background color or background image for the Excel document. Now, this article will introduce how to do this programmatically using Free Spire.XLS for Java.

Import the Jar dependency
Method 1: Download the Free Spire.XLS for Java and unzip it, then add the Spire.Xls.jar file to your project as dependency.

Method 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>3.9.1</version>
    </dependency>
</dependencies>

Set background color:

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.getRange().getStyle().setColor(Color.pink);
        //Set background color for a specified cell range in the worksheet
        //sheet.getCellRange("A1:E19").getStyle().setColor(Color.yellow);

        //Save the file
        workbook.saveToFile("SetBackColor.xlsx", ExcelVersion.Version2013);
    }
}

BgColor.jpg

Set background image:

import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class BackgroundImage {
    public static void main(String[] args) throws IOException {
        //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);
        //Load an image
        BufferedImage image = ImageIO.read( new File("C:\\Users\\Administrator\\Desktop\\bg.jpg"));
        //Set the image as the background image of the worksheet
        sheet.getPageSetup().setBackgoundImage(image);

        //Save the file
        workbook.saveToFile("SetBackImage.xlsx", ExcelVersion.Version2013);
    }
}

bgImage.jpg