Friday, 30 July 2021

Insert an OLE object to an Excel worksheet using Java codes

Recently, I find a free third-party library called Free Spire.Office for Java and it supports inserting Word/Excel/PowerPoint/PDF documents as linked object or embedded object into Excel worksheets. This article will show how to insert a Word document as an embedded object into Excel using Java codes with the help of it.

DEPENDENCY

First of all, we need to download and install JDK and Intellij IDEA to create a development environment. Then we get the package of the free library from the official website, find Spire.Xls.jar in the “lib” folder. Finally, manually add it to IDEA.

Besides, there is another way to add the Jar file, which is using the following codes in the Maven Pom.xml file.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.office.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

USING THE CODE

import com.spire.xls.*;
import com.spire.xls.core.IOleObject;
import com.spire.doc.*;
import com.spire.doc.documents.ImageType;
import java.awt.image.BufferedImage;

public class InsertOLE {
public static void main(String[] args) {

//Load the Excel document
Workbook workbook = new Workbook();
workbook.loadFromFile(
"C:\\Users\\Test1\\Desktop\\Sample.xlsx");
//Get the first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);

//Generate image
BufferedImage image = GenerateImage("C:\\Users\\Test1\\Desktop\\Test.docx");
//insert OLE object
IOleObject oleObject = worksheet.getOleObjects().add("C:\\Users\\Test1\\Desktop\\Test.docx", image, OleLinkType.Embed);
oleObject.setLocation(worksheet.getCellRange(
"B4"));
oleObject.setObjectType(OleObjectType.
ExcelWorksheet);
//Save the file
workbook.saveToFile("output/InsertOLE.xlsx", ExcelVersion.Version2010);
}

private static BufferedImage GenerateImage(String fileName) {

//Load the sample word document
Document document = new Document();
document.loadFromFile(fileName);

//Save the first page of word as an image
BufferedImage image = document.saveToImages(0, ImageType.Bitmap);
return image;
}
}

Output






No comments:

Post a Comment

Change PDF Versions in Java

In daily work, you might need to change the version of a PDF document you have in order to ensure compatibility with another version which a...