</>

Technology

Selenium

Difficulty

Intermediate

Interview Question

Name an API used for reading and writing data to Excel files in Selenium.

Apache POI and JXL (Java Excel API) are the most popular Java APIs for reading, writing, and updating Excel files in Selenium automation.

Answer

APIs for Reading and Writing Excel Files

Two main APIs are used in Java Selenium projects to handle Excel data:

1. Apache POI (Most Popular) Apache POI is an open-source Java library for Microsoft Office documents, including .xls and .xlsx files.

Java
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFCell;
import java.io.FileInputStream;

public class ExcelReader {

    public static String readCell(String filePath, String sheetName, int row, int col) throws Exception {
        FileInputStream fis = new FileInputStream(filePath);
        XSSFWorkbook wb = new XSSFWorkbook(fis);
        XSSFSheet sheet = wb.getSheet(sheetName);
        XSSFRow rowObj = sheet.getRow(row);
        String cellValue = rowObj.getCell(col).getStringCellValue();
        wb.close();
        return cellValue;
    }

    public static void writeCell(String filePath, String sheetName, int row, int col, String value) throws Exception {
        FileInputStream fis = new FileInputStream(filePath);
        XSSFWorkbook wb = new XSSFWorkbook(fis);
        XSSFSheet sheet = wb.getSheet(sheetName);
        sheet.getRow(row).getCell(col).setCellValue(value);
        FileOutputStream fos = new FileOutputStream(filePath);
        wb.write(fos);
        wb.close();
    }
}

POI class hierarchy:

File typeWorkbookSheetRowCell
.xls (old)HSSFWorkbookHSSFSheetHSSFRowHSSFCell
.xlsx (new)XSSFWorkbookXSSFSheetXSSFRowXSSFCell

Maven dependency:

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

2. JXL (Java Excel API) JXL is an older, lighter API that supports only .xls (not .xlsx) format.

Java
import jxl.Workbook;
import jxl.Sheet;

Workbook wb = Workbook.getWorkbook(new File("data.xls"));
Sheet sheet = wb.getSheet("Sheet1");
String value = sheet.getCell(col, row).getContents();
wb.close();

Apache POI vs JXL:

FeatureApache POIJXL
.xlsx supportYesNo
.xls supportYesYes
Actively maintainedYesNo
Usage in projectsStandardLegacy

Recommendation: Use Apache POI for all new projects — it supports modern .xlsx files and is actively maintained.

Follow AutomateQA

Related Topics