Technology

read data from excel in selenium

Selenium is one of the most popular tools for automating web browsers. It allows testers and developers to automate their browser actions and execute web application testing efficiently. A common scenario in automated testing is the need to read test data from an Excel sheet. This data can be used to drive test cases, which makes tests more dynamic and manageable. In this topic, we will explore how to read data from an Excel file in Selenium using Java.

Understanding Selenium and Excel Integration

Selenium is a widely used tool for automating web browsers across various programming languages. While Selenium itself is great for automating browser actions, it doesn’t have a built-in feature for reading data from Excel. Fortunately, we can integrate Selenium with Apache POI, a popular library for handling Excel files in Java. Apache POI allows us to read and write data to Excel files and is highly compatible with Selenium.

By combining Selenium with Apache POI, we can make our tests more flexible and dynamic, as we can read input data from Excel sheets and use it for test case execution. This approach helps in managing large sets of data for automated tests and allows the same tests to run with different sets of input.

Prerequisites for Reading Excel Data in Selenium

Before you can start reading data from Excel in Selenium, there are a few things you need:

1. Apache POI Library

To read Excel files in Java, we use the Apache POI library. This library provides the necessary methods to interact with both .xls (HSSF) and .xlsx (XSSF) formats. To get started, you need to add Apache POI to your Selenium project.

You can download the necessary Apache POI jars or add the dependency via Maven.

Maven Dependency:

<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>5.2.3</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>5.2.3</version></dependency>

2. Java Setup for Selenium

Ensure that Selenium WebDriver is correctly set up in your Java project. You can include Selenium WebDriver in your Maven project with the following dependency:

Maven Dependency for Selenium:

<dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-java</artifactId><version>4.4.0</version></dependency>

Once the necessary libraries are added, you can begin reading data from Excel files.

Steps to Read Data from Excel in Selenium

Let’s break down the process of reading data from an Excel file step by step.

1. Set Up the Excel File

Make sure your Excel file is structured correctly with columns containing the data you want to read. For instance, consider an Excel file that contains login credentials such as:

Username Password
testuser1 password1
testuser2 password2

2. Import Required Libraries

To begin, you’ll need to import the necessary libraries for working with Selenium and Apache POI. These libraries are used for web automation and reading Excel files, respectively.

import org.apache.poi.ss.usermodel.*;import org.apache.poi.xssf.usermodel.XSSFWorkbook;import org.openqa.selenium.WebDriver;import org.openqa.selenium.chrome.ChromeDriver;import java.io.File;import java.io.FileInputStream;import java.io.IOException;

3. Set Up Selenium WebDriver

Next, set up your WebDriver. For this example, we will use ChromeDriver.

System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");WebDriver driver = new ChromeDriver();

4. Open the Excel File

Before you can read data from Excel, you need to load the file using FileInputStream and then create an instance of XSSFWorkbook (for .xlsx files).

FileInputStream fis = new FileInputStream(new File("path/to/excel/file.xlsx"));XSSFWorkbook workbook = new XSSFWorkbook(fis);

5. Access the Specific Sheet

In Excel, each sheet is a tab that contains rows and columns. You need to specify the sheet you want to read from.

Sheet sheet = workbook.getSheetAt(0);  // Accessing the first sheet

6. Loop Through Rows and Columns

Once you have the sheet, you can loop through the rows and columns to read the data. Each row contains data in cells, and each cell can hold values such as text or numbers. In the example, we will read the username and password columns.

for (int i = 1; i <= sheet.getPhysicalNumberOfRows(); i++) {Row row = sheet.getRow(i);String username = row.getCell(0).getStringCellValue();  // Reading the first column (username)String password = row.getCell(1).getStringCellValue();  // Reading the second column (password)// Perform operations with the data (e.g., logging into a website)driver.get("https://example.com/login");driver.findElement(By.name("username")).sendKeys(username);driver.findElement(By.name("password")).sendKeys(password);driver.findElement(By.name("submit")).click();}

7. Close the Excel File

After reading the data, it is good practice to close the Excel file and release resources.

workbook.close();fis.close();

8. Running the Test

Now, when you run the test, Selenium will read data from the Excel file, populate the fields, and simulate login attempts based on the input data.

Handling Different Excel Formats

Apache POI supports two formats for Excel files:

1. XLS Format (HSSF)

If you are working with older .xls files, you will use HSSFWorkbook instead of XSSFWorkbook.

HSSFWorkbook workbook = new HSSFWorkbook(fis);

2. XLSX Format (XSSF)

If you are working with the newer .xlsx format, you use XSSFWorkbook, as demonstrated in the previous examples.

Error Handling

When working with Excel files, it’s essential to handle potential exceptions. Here are some common exceptions you should handle:

  • FileNotFoundException: This occurs when the specified Excel file is not found.

  • IOException: This occurs when there is an issue with reading or writing the Excel file.

  • NullPointerException: This occurs when trying to access a cell or row that doesn’t exist.

You can handle these exceptions using try-catch blocks.

try {FileInputStream fis = new FileInputStream(new File("path/to/excel/file.xlsx"));XSSFWorkbook workbook = new XSSFWorkbook(fis);} catch (IOException e) {e.printStackTrace();}

Reading data from an Excel file in Selenium can significantly enhance your automated testing workflows. By leveraging Apache POI, you can efficiently extract data from Excel sheets and use it in your Selenium test cases. This makes your tests more dynamic, reusable, and easier to maintain. Whether you’re automating form submissions, login tests, or data-driven test scenarios, integrating Excel with Selenium gives you more flexibility and control over your test data.

As Selenium continues to be a powerful tool in browser automation, combining it with Excel files opens up new possibilities for more robust and dynamic test automation strategies.