When manipulating an Excel document, we can extract cell values by simply copying and pasting. Alternatively, we can also obtain it programmatically in Java application, which can greatly save time and improve efficiency. In this tutorial, you will learn how to extract the value of a specified cell by its name using a free Java API.
Install the free API (2 Method)
1# Download the free API (Free Spire.XLS for Java) and unzip it, then add the Spire.Xls.jar file to your project as dependency.
2# Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://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>
Get Cell Values by Cell Names in Excel
The detailed steps and complete code are as follows:
- Create a Workbook instance.
- Load an Excel sample document using Workbook.loadFromFile() method.
- Get a specified worksheet using Workbook.getWorksheets().get() method.
- Get a specific cell by its name using Worksheet.getRange().get() method.
- Create a StringBulider instance.
- Get 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( "member.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Get the specified cell by its name
CellRange cell = sheet.getRange().get("C3");
//Create a StringBuilder instance
StringBuilder content = new StringBuilder();
//Get value of the cell "D6"
content.append("The value of cell C3 is: " + cell.getValue()+"\n");
System.out.println(content);
}
}