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

Enterprise AI Trend Report: Gain insights on ethical AI, MLOps, generative AI, large language models, and much more.

2024 Cloud survey: Share your insights on microservices, containers, K8s, CI/CD, and DevOps (+ enter a $750 raffle!) for our Trend Reports.

PostgreSQL: Learn about the open-source RDBMS' advanced capabilities, core components, common commands and functions, and general DBA tasks.

AI Automation Essentials. Check out the latest Refcard on all things AI automation, including model training, data security, and more.

Related

  • The Generic Way To Convert Between Java and PostgreSQL Enums
  • Building REST API Backend Easily With Ballerina Language
  • The Complete Guide to Stream API and Collectors in Java 8
  • Harnessing the Power of SIMD With Java Vector API

Trending

  • Role-Based Multi-Factor Authentication
  • Implementing CI/CD Pipelines With Jenkins and Docker
  • The Rise of the Platform Engineer: How to Deal With the Increasing Complexity of Software
  • Behavior-Driven Development (BDD) Framework for Terraform
  1. DZone
  2. Coding
  3. Java
  4. How To Get Cell Data From an Excel Spreadsheet Using APIs in Java

How To Get Cell Data From an Excel Spreadsheet Using APIs in Java

This article discusses the benefits OpenXML document formatting offers developers and suggests two API solutions for programmatically retrieving Excel data.

By 
Brian O'Neill user avatar
Brian O'Neill
DZone Core CORE ·
Dec. 05, 23 · Tutorial
Like (7)
Save
Tweet
Share
5.8K Views

Join the DZone community and get the full member experience.

Join For Free

Our Excel spreadsheets hold a lot of valuable data in their dozens, hundreds, or even thousands of cells and rows.  With that much clean, formatted digital data at our disposal, it’s up to us to find programmatic methods for extracting and sharing that data among other important documents in our file ecosystem.

Thankfully, Microsoft made that extremely easy to do when they switched their file representation standard over to OpenXML more than 15 years ago.  This open-source XML-based approach drastically improved the accessibility of all Office document contents by basing their structure on well-known technologies – namely Zip and XML – which most software developers intimately understand.  Before that, Excel (XLS) files were stored in a binary file format known as BIFF (Binary Interchange File Format), and other proprietary binary formats were used to represent additional Office files like Word (DOC).

This change to an open document standard made it possible for developers to build applications that could interact directly with Office documents in meaningful ways. To get information about the structure of a particular Excel workbook, for example, a developer could write code to access xl/workbook.xml in the XLSX file structure and get all the workbook metadata they need. Similarly, to get specific sheet data, they could access xl/worksheets/(sheetname).xml, knowing that each cell and value with that sheet will be represented by simple <c> and <v> elements with all their relevant data nested within.  This is a bit of an oversimplification, but it serves to point out the ease of navigating a series of zipped XML file paths.

Given the global popularity of Excel files, building (or simply expanding) applications to load, manipulate, and extract content from XLSX was a no-brainer. There are dozens of examples of modern applications that can seamlessly load & manipulate XLSX files, and many even provide the option to export files in XLSX format.  

When we set out to build our applications to interact with Excel documents, we have several options at our disposal.  We can elect to write our code to sift through OpenXML document formatting, or we can download a specialized programming library, or we can alternatively call a specially designed web API to take care of a specific document interaction on our behalf.   The former two options can help us keep our code localized, but they’ll chew up a good amount of keyboard time and prove a little more costly to run.  With the latter option, we can offload our coding and processing overhead to an external service, reaping all the benefits with a fraction of the hassle.  Perhaps most beneficially, we can use APIs to save time and rapidly get our application prototypes off the ground.

Demonstration

In the remainder of this article, I’ll quickly demonstrate two free-to-use web APIs that allow us to retrieve content from specific cells in our XLSX spreadsheets in slightly different ways.  Ready-to-run Java code is available below to make structuring our calls straightforward.

Both APIs will return information about our target cell, including the cell path, cell text value, cell identifier, cell style index, and the formula (if any) used within that cell.   With the information in our response object, we can subsequently ask our applications to share data between spreadsheets and other open standard files for myriad purposes.  

Conveniently, both API requests can be authorized with the same free API key. It’s also important to note that both APIs process file data in memory and release that data upon completion of the request.  This makes both requests fast and extremely secure.

The first of these two API solutions will locate the data we want using the row index and cell index in our request.  The second solution will instead use the cell identifier (i.e., A1, B1, C1, etc.) for the same purpose.  While cell index and cell identifier are often regarded interchangeably (both locate a specific cell in a specific location within an Excel worksheet), using the cell index can make it easier for our application to adapt dynamically to any changes within our document, while the cell identifier will always remain static.

To use these APIs, we’ll start by installing the SDK with Maven.  We can first add a reference to the repository in pom.xml:

XML
 
<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>


We can then add 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 installation out of the way, we can structure our request parameters and use ready-to-run Java code examples to make our API calls.  To retrieve cell data using the row index and cell index, we can format our request parameters like the application/JSON example below:

JSON
 
{
  "InputFileBytes": "string",
  "InputFileUrl": "string",
  "WorksheetToQuery": {
    "Path": "string",
    "WorksheetName": "string"
  },
  "RowIndex": 0,
  "CellIndex": 0
}


And we can use the below code to call the API once our parameters are set:

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();
GetXlsxCellRequest input = new GetXlsxCellRequest(); // GetXlsxCellRequest | Document input request
try {
    GetXlsxCellResponse result = apiInstance.editDocumentXlsxGetCellByIndex(input);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling EditDocumentApi#editDocumentXlsxGetCellByIndex");
    e.printStackTrace();
}


To retrieve cell data using the cell identifier, we can format our request parameters like the application/JSON example below:

JSON
 
{
  "InputFileBytes": "string",
  "InputFileUrl": "string",
  "WorksheetToQuery": {
    "Path": "string",
    "WorksheetName": "string"
  },
  "CellIdentifier": "string"
}


We can use the final code examples below to structure our API call once our parameters are set:

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();
GetXlsxCellByIdentifierRequest input = new GetXlsxCellByIdentifierRequest(); // GetXlsxCellByIdentifierRequest | Document input request
try {
    GetXlsxCellByIdentifierResponse result = apiInstance.editDocumentXlsxGetCellByIdentifier(input);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling EditDocumentApi#editDocumentXlsxGetCellByIdentifier");
    e.printStackTrace();
}


That’s all the code we’ll need.  With utility APIs at our disposal, we’ll have our projects up and running in no time.

API Data (computing) Java (programming language) Data Types Chrome Web Store Mobile Web Server applications Web Service XML database XML editor Doc (computing)

Opinions expressed by DZone contributors are their own.

Related

  • The Generic Way To Convert Between Java and PostgreSQL Enums
  • Building REST API Backend Easily With Ballerina Language
  • The Complete Guide to Stream API and Collectors in Java 8
  • Harnessing the Power of SIMD With Java Vector API

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send 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: