How To Get Images From Excel Documents Using APIs in Java
Using minimal, ready-to-run code, we can automate workflows that extract important image objects from Excel spreadsheets. Learn more in this article.
Join the DZone community and get the full member experience.
Join For FreeUnique images tend to spruce up Excel reports. When we receive a product sales report spreadsheet with relevant product images, for example, we might walk away with a stronger understanding of the physical item behind the fluctuating numbers.
When we build web applications to streamline Excel-related processes, automating workflows that extract and share relevant images between the multitude of reports living in our file storage ecosystem can significantly increase the efficiency of future projects – in much the same way extracting and sharing actual data sets can. This is especially true when we receive reports from external stakeholders containing image objects we don’t otherwise have immediate access to. If we can work out our own way to store relevant spreadsheet images in accessible locations for our business users, or even images directly into new, programmatically generated Excel files of our own, we can transform another normally-slow-moving, manual content collaboration task into a fully automated, time-saving system.
Thankfully, the OpenXML file structure XLSX is based on makes it easy to pinpoint and extract image objects from specific locations within an Excel document. After all, OpenXML files are essentially standard zip archives full of neatly compartmentalized folders and files, which means programmatically navigating a relatable file path structure is at the heart of our operation.
Background
To provide a little background, images (and other graphical elements) in Excel are displayed with instructions from the xl/drawings folder in OpenXML XLSX file structure. The actual image file objects themselves (such as PNG or JPG files added to the document) can be traced to the xl/media folder. When we open an Excel document with images, a markup language called DrawingML (Drawing Markup Language) dictates how and where we’ll see the image on a specific worksheet with the spreadsheet.
When we programmatically extract images from Excel documents, we’re simply unzipping the xl/media folder and retrieving one or more objects. Since we’re accessing fully formed objects, we can also retrieve key data about the image from our request, including the actual name of the file, the content type, the embed ID, and the file path.
While we could certainly write code in a variety of different programming languages to unzip Excel files and extract image objects ourselves, we could – depending on the context of our own project – also benefit from a low-code API solution to handle the operation for us.
In this article, I’ll demonstrate two easy-to-use API solutions that work together to simplify the process of extracting image objects from Excel files.
Demonstration
Using the ready-to-run Java code examples provided below, we can call two APIs back-to-back that will return file bytes for each image object stored within an XLSX file. To authorize our API calls, we’ll just need a free API key.
These APIs perform the following actions:
- Returning image objects are defined in an XLSX spreadsheet as a temporary URL.
- Converting the temporary URL to file bytes which can be written to a new file
In our first API call, we can optionally specify where in the XLSX document we want to retrieve images from. We can specify these instructions following the example JSON request format below:
{
"InputFileBytes": "string",
"InputFileUrl": "string",
"WorksheetToQuery": {
"Path": "string",
"WorksheetName": "string"
}
}
To customize the WorksheetToQuery
object, we’ll of course need to have information available about specific file paths or worksheet names. If we don’t specify the worksheet we want to query (i.e., if we leave the WorksheetToQuery
object blank), the operation will simply return all image objects present within the entire document.
Our API response will return one information object for each image, following the example JSON response object below:
{
"Successful": true,
"Images": [
{
"Path": "string",
"ImageDataEmbedId": "string",
"ImageDataContentType": "string",
"ImageInternalFileName": "string",
"ImageContentsURL": "string"
}
]
}
To call our first API, we can begin by installing the SDK. We can install with Maven by first adding a reference to the repository in pom.xml:
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
And then adding a reference to the dependency in pom.xml:
<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v4.25</version>
</dependency>
</dependencies>
With that out of the way, we can copy the imports and the subsequent function into our file. We can copy our API key into the indicated snippet, and we can then supply our custom request object (either containing a public Excel file URL or Excel file bytes):
// Import classes:
//import com.cloudmersive.client.invoker.ApiClient;
//import com.cloudmersive.client.invoker.ApiException;
//import com.cloudmersive.client.invoker.Configuration;
//import com.cloudmersive.client.invoker.auth.*;
//import com.cloudmersive.client.EditDocumentApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");
EditDocumentApi apiInstance = new EditDocumentApi();
GetXlsxImagesRequest input = new GetXlsxImagesRequest(); // GetXlsxImagesRequest | Document input request
try {
GetXlsxImagesResponse result = apiInstance.editDocumentXlsxGetImages(input);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling EditDocumentApi#editDocumentXlsxGetImages");
e.printStackTrace();
}
When this returns our temporary URL, we can then call the next function to convert the URL to image file bytes:
// Import classes:
//import com.cloudmersive.client.invoker.ApiClient;
//import com.cloudmersive.client.invoker.ApiException;
//import com.cloudmersive.client.invoker.Configuration;
//import com.cloudmersive.client.invoker.auth.*;
//import com.cloudmersive.client.EditDocumentApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");
EditDocumentApi apiInstance = new EditDocumentApi();
FinishEditingRequest reqConfig = new FinishEditingRequest(); // FinishEditingRequest | Cloudmersive Document URL to complete editing on
try {
byte[] result = apiInstance.editDocumentFinishEditing(reqConfig);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling EditDocumentApi#editDocumentFinishEditing");
e.printStackTrace();
}
We can now write our image file bytes to new image files (like PNG or JPEG) in our file storage system, or we can write a subsequent workflow to copy the image contents into a new document.
Opinions expressed by DZone contributors are their own.
Comments