DEV Community


Posted on

Java/ Add Image Comments to Excel

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 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.

Enter fullscreen mode Exit fullscreen mode

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;

public class ImageComment {
    public static void main(String[] args)throws IOException {
        //Load the sample Excel file
        Workbook workbook = new Workbook();
        //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 = 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
        //Show the comment

        //Save the document to file
        workbook.saveToFile("SetImageComment.xlsx", ExcelVersion.Version2013);
Enter fullscreen mode Exit fullscreen mode


Discussion (0)