</>

Technology

Selenium

Difficulty

Intermediate

Interview Question

Why and how will you use an Excel Sheet in your Selenium project?

Answer

Using Excel Sheets in Selenium Projects

Why use Excel? Excel sheets serve as a centralized, non-technical data source for test data. Business analysts or QA managers can update test data without touching code.

Primary use cases:

  1. Data-Driven Testing — Store login credentials, search terms, form values
  2. Test Data Management — Maintain datasets for multiple environments
  3. Result Storage — Write pass/fail status back to the sheet

How to use (Apache POI + TestNG @DataProvider):

Excel structure (testdata.xlsx):

usernamepasswordexpectedTitle
user1pass1Dashboard
user2pass2Dashboard
invaliduserwrongpassLogin Error

ExcelReader utility class:

Java
import org.apache.poi.xssf.usermodel.*;
import java.io.FileInputStream;

public class ExcelUtils {

    private XSSFWorkbook workbook;
    private XSSFSheet sheet;

    public ExcelUtils(String filePath, String sheetName) throws Exception {
        FileInputStream fis = new FileInputStream(filePath);
        workbook = new XSSFWorkbook(fis);
        sheet = workbook.getSheet(sheetName);
    }

    public String getCellData(int row, int col) {
        return sheet.getRow(row).getCell(col).getStringCellValue();
    }

    public int getRowCount() {
        return sheet.getLastRowNum();
    }
}

TestNG DataProvider reading from Excel:

Java
public class LoginTest {

    ExcelUtils excel;

    @DataProvider(name = "loginData")
    public Object[][] getLoginData() throws Exception {
        excel = new ExcelUtils("src/test/resources/testdata.xlsx", "LoginSheet");
        int rows = excel.getRowCount();
        Object[][] data = new Object[rows][2];

        for (int i = 1; i <= rows; i++) {
            data[i-1][0] = excel.getCellData(i, 0);  // username
            data[i-1][1] = excel.getCellData(i, 1);  // password
        }
        return data;
    }

    @Test(dataProvider = "loginData")
    public void loginTest(String username, String password) {
        driver.findElement(By.id("username")).sendKeys(username);
        driver.findElement(By.id("password")).sendKeys(password);
        driver.findElement(By.id("loginBtn")).click();
    }
}

Key benefits:

  • Non-developers can manage test data
  • No code recompilation when data changes
  • Single source of truth for test inputs
  • Scales easily to hundreds of data rows

Follow AutomateQA

Related Topics