Java/ Add Image Comments to Excel

Java/ Add Image Comments to Excel

·

2 min read

In Excel documents, you can add comments to specific cells to add additional information or explain the contents of the cells. In addition to adding a text comment to a cell using Free Spire.XLS for Java, this free API also supports adding image comment. In this article, you will learn how to accomplish this task in Java applications.

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# You can also 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>

Add Image Comments

The detailed steps and full code are as follows:

● Create a Workbook instance, and then load an Excel file using Workbook.loadFromFile() method.
● Get the first worksheet of the Excel file using Workbook.getWorksheets().get() method.
● Get a specific cell using Worksheet.getCellRange() method.
● Add a comment to that cell using Cellrange.addComment() method.
● Load an image and fill the comment with the image using ExcelComment.getFill().customPicture() method.
● Set the heigth/width of the comment and set to show the comment using the methods offered by ExcelComment class.
● Save the document to another file using Workbook.saveToFile() method.

import com.spire.xls.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

public class ImageComment {
    public static void main(String[] args)throws IOException {
        //Load the sample Excel file
        Workbook workbook = new Workbook();
        workbook.loadFromFile("member.xlsx");
        //Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);

        //Get the specific cell
        CellRange range = sheet.getCellRange("E7");
        //Add the commet
        ExcelComment comment = range.addComment();
        //Load an image
        BufferedImage bufferedImage = ImageIO.read(new File("C:\\Users\\Administrator\\Desktop\\flag.jpg"));
        //Use the image to fill the comment
        comment.getFill().customPicture(bufferedImage, "C:\\Users\\Administrator\\Desktop\\flag.jpg");

        //Set the height and width for the comment
        comment.setHeight(bufferedImage.getHeight());
        comment.setWidth(bufferedImage.getWidth());
        //Show the comment
        comment.setVisible(true);

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

ImageComment.jpg