Monday, 1 November 2021

Get Cell Values by Cell Names in Excel Using Java

In Excel documents, you can copy and paste cell data to extra values. Alternatively, they can also be obtained automatically with Java code, which will not only save time and improve efficiency, but ensure there will be no errors. In this tutorial, you will learn how to extract the value of a specified cell in Excel by its name with the help of a free third-party library called Free Spire.XLS for Java.

DEPENDENCY

First of all, you need to add Spire.Xls.jar as a dependency in your Java program. The JAR file can be downloaded from this link, or you can directly create Maven in your project, and then add the following in the 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.xls.free</artifactId>
<version>3.9.1</version>
</dependency>
</dependencies>

USING THE CODE

Free Spire.XLS for Java supports getting a specified cell in Excel by its name using Worksheet.getRange().get() method, and then obtaining the cell value using  CellRange.getValue() method. You can find the detailed steps as below.

l  Create a Workbook instance.

l  Load an Excel sample document using Workbook.loadFromFile() method.

l  Get a specified worksheet using Workbook.getWorksheets().get() method.

l  Get a specific cell by its name using Worksheet.getRange().get() method.

l  Create a StringBulider instance.

l  Obtain the cell value using CellRange.getValue() method, and then append the value to the StringBuilder instance using StringBuilder.append() method.

import com.spire.xls.*;

public class GetCellValue {
public static void main(String[] args) {
//Create a Workbook instance
Workbook workbook = new Workbook();

//Load an Excel sample document
workbook.loadFromFile( "C:\\Users\\Test1\\Desktop\\sample.xlsx");

//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);

//Get a specified cell by its name
CellRange cell = sheet.getRange().get("C5");

//Create a StringBuilder instance
StringBuilder content = new StringBuilder();

//Get value of the cell "C5"
content.append("The value of cell C5 is: " + cell.getValue()+"\n");

System.out.println(content);
}
}

input 

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