Java: Get Cell Values by Cell Names in Excel

To extract values from an Excel document, you can copy and paste cell data. Alternatively, you can obtain it automatically by utilizing 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 by its name using Spire.XLS for Java.

Install Spire.XLS for Java

First of all, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's 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</artifactId>
        <version>14.3.2</version>
    </dependency>
</dependencies>
    

Get Cell Values by Cell Names in Excel

Spire.XLS for Java offers Worksheet.getRange().get() method to specify a cell in Excel by its name, and CellRange.getValue() method to obtain the cell value. The detailed steps are listed as below.

  • 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.
  • Obtain the cell value using CellRange.getValue() method, and then append the value to the StringBuilder instance using StringBuilder.append() method.
  • Java
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 the specified cell by its name
        CellRange cell = sheet.getRange().get("D6");
       
        //Create a StringBuilder instance
        StringBuilder content = new StringBuilder();

        //Get value of the cell "D6" 
        content.append("The value of cell D6 is: " + cell.getValue()+"\n");
 
//Output the result
        System.out.println(content);
    }
}

The input Excel:

Java: Get Cell Values by Cell Names in Excel

The output result:

Java: Get Cell Values by Cell Names in Excel

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.