How to set and update cell contents in an Excel XLSX by index in Java
2 min readFeb 13, 2020
Editing Excel files is a crucial feature for many types of applications, but implementation can be difficult to set up. That’s why today’s post will show you how to get things rolling quickly and easily using an API.
Library installation is first on the agenda. To allow Jitpack to take care of this for us, add these two references to you pom.xml file.
Repository reference:
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Dependency reference:
<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v3.34</version>
</dependency>
</dependencies>
Continuing on, we invoke editDocumentXlsxSetCellByIndex:
// 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: ApikeyApiKeyAuth 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();SetXlsxCellRequest input = new SetXlsxCellRequest(); // SetXlsxCellRequest | Document input requesttry {SetXlsxCellResponse result = apiInstance.editDocumentXlsxSetCellByIndex(input);System.out.println(result);} catch (ApiException e) {System.err.println("Exception when calling EditDocumentApi#editDocumentXlsxSetCellByIndex");e.printStackTrace();}
Then provide an input in this format:
{
"InputFileBytes": "string",
"InputFileUrl": "string",
"WorksheetToUpdate": {
"Path": "string",
"WorksheetName": "string"
},
"RowIndex": 0,
"CellIndex": 0,
"CellValue": {
"Path": "string",
"TextValue": "string",
"CellIdentifier": "string",
"StyleIndex": 0,
"Formula": "string"
}
}
And our API will make the requested change. Not bad, right?