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.
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 type | Workbook | Sheet | Row | Cell |
|---|---|---|---|---|
.xls (old) | HSSFWorkbook | HSSFSheet | HSSFRow | HSSFCell |
.xlsx (new) | XSSFWorkbook | XSSFSheet | XSSFRow | XSSFCell |
Maven dependency:
<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.
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:
| Feature | Apache POI | JXL |
|---|---|---|
| .xlsx support | Yes | No |
| .xls support | Yes | Yes |
| Actively maintained | Yes | No |
| Usage in projects | Standard | Legacy |
Recommendation: Use Apache POI for all new projects — it supports modern .xlsx files and is actively maintained.
