DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • How To Add, Remove, or Rotate Pages in a PDF Document Using Java
  • How To Perform OCR on a Photograph of a Receipt Using Java
  • How to Merge HTML Documents in Java
  • Thumbnail Generator Microservice for PDF in Spring Boot

Trending

  • Integrating Model Context Protocol (MCP) With Microsoft Copilot Studio AI Agents
  • How to Ensure Cross-Time Zone Data Integrity and Consistency in Global Data Pipelines
  • Simpler Data Transfer Objects With Java Records
  • Mastering Deployment Strategies: Navigating the Path to Seamless Software Releases
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. How To Get Images From Excel Documents Using APIs in Java

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.

By 
Brian O'Neill user avatar
Brian O'Neill
DZone Core CORE ·
Feb. 26, 24 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
2.3K Views

Join the DZone community and get the full member experience.

Join For Free

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

  1. Returning image objects are defined in an XLSX spreadsheet as a temporary URL.
  2. 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:

JSON
 
{
  "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:

JSON
 
{
  "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:

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:

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

Java
 
// 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:

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

API Document Data Types

Opinions expressed by DZone contributors are their own.

Related

  • How To Add, Remove, or Rotate Pages in a PDF Document Using Java
  • How To Perform OCR on a Photograph of a Receipt Using Java
  • How to Merge HTML Documents in Java
  • Thumbnail Generator Microservice for PDF in Spring Boot

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!