Adding an Image to a Cell in an Excel File Using Java

06 May 2023 Balmiki Mandal 0 Core Java

How to Add an Image to a Cell in an Excel File With Java

Adding an image to a cell in an Excel file with Java is quite easy. In this tutorial, we will show you how to accomplish this task using Apache POI library. Apache POI is an open-source Java API for manipulating various file formats based upon the Office Open XML standards (OOXML) and Microsoft's OLE 2 Compound Document format (OLE2).

Requirements

  • Java JDK 8 or higher
  • Apache POI 4.1.0 or higher
  • Maven 3.6.1 or higher

Steps

  1. Create a folder in your project directory and name it “resources”. This is where you will add the image you would like to display in your Excel file. The image file must be in the JPG or PNG format.
  2. Create a new Maven project in your favorite IDE. Add the following dependency to your pom.xml file:
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>4.1.0</version>
    </dependency>
  3. Create a class named “AddImageToExcel.java” in the “src/main/java” package.
  4. In the “AddImageToExcel.java” class, declare the input stream, workbook, and drawing objects as follows:
    InputStream inputStream = null;
    Workbook workbook = null;
    Drawing drawing = null;
  5. Create an instance of the workbook and drawing objects by passing the input stream of the Excel file as an argument:
    workbook = WorkbookFactory.create(inputStream);
    drawing = (HSSFPicture) workbook.getSheetAt(0).createDrawingPatriarch();
  6. Create an instance of the “CreationHelper” class, which helps in creating pictures in a workbook:
    CreationHelper helper = workbook.getCreationHelper();
  7. Create a client anchor object by passing the row and column numbers to the “createClientAnchor” method of the “helper” object:
    ClientAnchor anchor = helper.createClientAnchor();
    anchor.setCol1(columnNumber);
    anchor.setRow1(rowNumber);
  8. Create a picture object by passing the input stream of the image file, the “anchor” object, and the index of the picture in the workbook as arguments to the “addPicture” method of the “drawing” object:
    Picture pict = drawing.createPicture(anchor, workbook.addPicture(image, Workbook.PICTURE_TYPE_JPEG));
  9. Close the input stream, write the updated Excel file to a file, and close the workbook instance:
    inputStream.close();
    FileOutputStream out = new FileOutputStream("MyExcel.xlsx");
    workbook.write(out);
    workbook.close();

Conclusion

In this tutorial, we have explained how to add an image to a cell in an Excel file with Java. We have also covered how to use Apache POI library to manipulate various file formats in Java. If you have any questions or suggestions, please feel free to leave a comment below.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.