Java/ Insert and Extract Image in Excel

NateBennett
2 min readDec 16, 2020

--

Excel is one of the most commonly used tool for us to process data, but sometimes we also need to insert an image in it for decoration purpose or to make the data analysis easier. This article will demonstrate how to insert and extract image in Excel file with the help of Free Spire.XLS for Java.

Installation
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: 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>

Insert Image

import com.spire.xls.*;

public class AddImage {
public static void main(String[] args) {
//Load an Excel file
Workbook wb = new Workbook();
wb.loadFromFile("test1.xlsx");

//Get the first worksheet
Worksheet sheet = wb.getWorksheets().get(0);

//Add an image to the specific cell
ExcelPicture picture = sheet.getPictures().add(5,1,"C:\\Users\\Administrator\\Desktop\\pic1.jpg");
//Set image width and height
picture.setHeight(270);
picture.setWidth(400);
//Set image rotation angle and hyperlink
//picture.setRotation(20);
//picture.setHyperLink("https://www.google.com",true);

//Save the result file
wb.saveToFile("AddImage.xlsx", ExcelVersion.Version2010);
wb.dispose();
}
}

Extract Image

import com.spire.xls.ExcelPicture;
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 ReadImage {
public static void main(String[] args) throws IOException {
//Load an Excel file
Workbook workbook = new Workbook();
workbook.loadFromFile("AddImage.xlsx");

//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);

//Get the first image in the worksheet
ExcelPicture pic = sheet.getPictures().get(0);
BufferedImage loImage = pic.getPicture();
//Save to disk
ImageIO.write(loImage,"jpg",new File("output/ReadImage.jpg"));
}
}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

NateBennett
NateBennett

Written by NateBennett

Sharing code to help developers deal with office files

No responses yet

Write a response