How to Read/Write Excel Data in Selenium Using Apache POI

โšก Smart Summary

Excel files drive Selenium data-driven tests, and Apache POI is the Java library that reads and writes them. The sections below cover the dependency, core classes, read and write examples, and JXL.

  • ๐Ÿ”˜ Two formats: HSSF classes handle .xls, XSSF classes handle .xlsx.
  • โœ… Core interfaces: Workbook, Sheet, Row and Cell mirror a spreadsheet.
  • ๐Ÿงช Reading: FileInputStream plus getLastRowNum loops every row and cell.
  • ๐Ÿ› ๏ธ Writing: createRow and setCellValue append data, FileOutputStream saves it.
  • ๐Ÿ“Š Legacy: JXL reads old workbooks but not XLSX.

Reading and writing Excel data in Selenium with Apache POI

File IO is a critical part of any software process. We frequently create a file, open it & update something or delete it in our Computers. Same is the case with Selenium Automation. We need a process to manipulate files with Selenium.

Java provides us different classes for File Manipulation with Selenium. In this tutorial, we are going to learn how can we read and write on Excel file with the help of Java IO package and Apache POI library.

Apache POI in Selenium

The Apache POI in Selenium is a widely used API for Selenium data driven testing. It is a POI library written in Java that gives users an API for manipulating Microsoft documents like .xls and .xlsx. Users can easily create, modify and read/write into Excel files. POI stands for “Poor Obfuscation Implementation.”

How to Handle Excel File Using POI (Maven POM Dependency)

POI links a Selenium test to the workbook below.

Apache POI acting as the bridge between a Selenium test and an Excel workbook

To Read and Write Excel file in Java, Apache provides a very famous library POI. This library is capable enough to read and write both XLS and XLSX file format of Excel.

To read XLS files, an HSSF implementation is provided by POI library.

To read XLSX, XSSF implementation of POI library will be the choice. Let’s study these implementations in detail.

If you are using Maven in your project, the Maven dependency will be added to pom.xml as shown below.

POI dependency entry added to the pom.xml file of a Maven project

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.1</version>
</dependency>

Version note: 4.1.1 is the original example; current projects declare poi-ooxml 5.5.1, which is required for XLSX.

Or you can simply download the latest version POI jars from http://poi.apache.org/download.html & download the latest zip file

Apache POI download page listing the binary and source distribution archives

When you download the zip file for this jar, you need to unzip it and add these all jars to the class path of your project.

Unzipped POI jar files added to the Java build path of the project

Classes and Interfaces in POI

Following is a list of different Java Interfaces and classes in POI for reading XLS and XLSX file, shown below-

POI class hierarchy from Workbook down to Sheet, Row and Cell

  • Workbook: XSSFWorkbook and HSSFWorkbook classes implement this interface.
  • XSSFWorkbook: Is a class representation of XLSX file.
  • HSSFWorkbook: Is a class representation of XLS file.
  • Sheet: XSSFSheet and HSSFSheet classes implement this interface.
  • XSSFSheet: Is a class representing a sheet in an XLSX file.
  • HSSFSheet: Is a class representing a sheet in an XLS file.
  • Row: XSSFRow and HSSFRow classes implement this interface.
  • XSSFRow: Is a class representing a row in the sheet of XLSX file.
  • HSSFRow: Is a class representing a row in the sheet of XLS file.
  • Cell: XSSFCell and HSSFCell classes implement this interface.
  • XSSFCell: Is a class representing a cell in a row of XLSX file.
  • HSSFCell: Is a class representing a cell in a row of XLS file.

Read/Write Operation

For our example, we will consider below given Excel file format

Sample ExportExcel workbook with the ExcelGuru99Demo sheet used by both examples

Read Data from Excel File

Complete Example: Here we are trying to read data from Excel in Selenium:

package excelExportAndFileIO;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.ss.usermodel.Sheet;

import org.apache.poi.ss.usermodel.Workbook;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadGuru99ExcelFile {

    public void readExcel(String filePath,String fileName,String sheetName) throws IOException{

    //Create an object of File class to open xlsx file

    File file =    new File(filePath+"\\"+fileName);

    //Create an object of FileInputStream class to read excel file

    FileInputStream inputStream = new FileInputStream(file);

    Workbook guru99Workbook = null;

    //Find the file extension by splitting file name in substring  and getting only extension name

    String fileExtensionName = fileName.substring(fileName.indexOf("."));

    //Check condition if the file is xlsx file

    if(fileExtensionName.equals(".xlsx")){

    //If it is xlsx file then create object of XSSFWorkbook class

    guru99Workbook = new XSSFWorkbook(inputStream);

    }

    //Check condition if the file is xls file

    else if(fileExtensionName.equals(".xls")){

        //If it is xls file then create object of HSSFWorkbook class

        guru99Workbook = new HSSFWorkbook(inputStream);

    }

    //Read sheet inside the workbook by its name

    Sheet guru99Sheet = guru99Workbook.getSheet(sheetName);

    //Find number of rows in excel file

    int rowCount = guru99Sheet.getLastRowNum()-guru99Sheet.getFirstRowNum();

    //Create a loop over all the rows of excel file to read it

    for (int i = 0; i < rowCount+1; i++) {

        Row row = guru99Sheet.getRow(i);

        //Create a loop to print cell values in a row

        for (int j = 0; j < row.getLastCellNum(); j++) {

            //Print Excel data in console

            System.out.print(row.getCell(j).getStringCellValue()+"|| ");

        }

        System.out.println();
    } 

    }  

    //Main function is calling readExcel function to read data from excel file

    public static void main(String...strings) throws IOException{

    //Create an object of ReadGuru99ExcelFile class

    ReadGuru99ExcelFile objExcelFile = new ReadGuru99ExcelFile();

    //Prepare the path of excel file

    String filePath = System.getProperty("user.dir")+"\\src\\excelExportAndFileIO";

    //Call read file method of the class to read data

    objExcelFile.readExcel(filePath,"ExportExcel.xlsx","ExcelGuru99Demo");

    }

}

Note: We are not using the TestNG framework here. Run the class as Java Application using function read excel in Selenium as shown in above example.

The console then prints every row, cell by cell.

Console output showing each Excel row printed with cell values separated by pipes

Write Data on Excel File

Complete Example: Here we are trying to write data from Excel file by adding new row in Excel file

package excelExportAndFileIO;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.ss.usermodel.Sheet;

import org.apache.poi.ss.usermodel.Workbook;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class WriteGuru99ExcelFile {

    public void writeExcel(String filePath,String fileName,String sheetName,String[] dataToWrite) throws IOException{

        //Create an object of File class to open xlsx file

        File file =    new File(filePath+"\\"+fileName);

        //Create an object of FileInputStream class to read excel file

        FileInputStream inputStream = new FileInputStream(file);

        Workbook guru99Workbook = null;

        //Find the file extension by splitting  file name in substring and getting only extension name

        String fileExtensionName = fileName.substring(fileName.indexOf("."));

        //Check condition if the file is xlsx file

        if(fileExtensionName.equals(".xlsx")){

        //If it is xlsx file then create object of XSSFWorkbook class

        guru99Workbook = new XSSFWorkbook(inputStream);

        }

        //Check condition if the file is xls file

        else if(fileExtensionName.equals(".xls")){

            //If it is xls file then create object of XSSFWorkbook class

            guru99Workbook = new HSSFWorkbook(inputStream);

        }    

    //Read excel sheet by sheet name    

    Sheet sheet = guru99Workbook.getSheet(sheetName);

    //Get the current count of rows in excel file

    int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum();

    //Get the first row from the sheet

    Row row = sheet.getRow(0);

    //Create a new row and append it at last of sheet

    Row newRow = sheet.createRow(rowCount+1);

    //Create a loop over the cell of newly created Row

    for(int j = 0; j < row.getLastCellNum(); j++){

        //Fill data in row

        Cell cell = newRow.createCell(j);

        cell.setCellValue(dataToWrite[j]);

    }

    //Close input stream

    inputStream.close();

    //Create an object of FileOutputStream class to create write data in excel file

    FileOutputStream outputStream = new FileOutputStream(file);

    //write data in the excel file

    guru99Workbook.write(outputStream);

    //close output stream

    outputStream.close();
	
    }

    public static void main(String...strings) throws IOException{

        //Create an array with the data in the same order in which you expect to be filled in excel file

        String[] valueToWrite = {"Mr. E","Noida"};

        //Create an object of current class

        WriteGuru99ExcelFile objExcelFile = new WriteGuru99ExcelFile();

        //Write the file using file name, sheet name and the data to be filled

        objExcelFile.writeExcel(System.getProperty("user.dir")+"\\src\\excelExportAndFileIO","ExportExcel.xlsx","ExcelGuru99Demo",valueToWrite);

    }

}

The workbook then carries the appended row.

Excel sheet after the new row with Mr. E and Noida has been appended

Excel Manipulation Using JXL API

JXL is also another famous jar to read Excel file in Java and writing files. Nowadays, POI is used in most of the projects, but before POI, JXL was only Java API for Excel manipulation. It is a very small and simple API for excel reading in Selenium.

JXL jar file listed among the project libraries

TIPS: My suggestion is not to use JXL in any new project because the library is not in active development from 2010 โ€” 2.6.12 is still its latest release โ€” and lack of the feature in compare to POI API.

Download JXL:

If you want to work with JXL, you can download it from this link

https://sourceforge.net/projects/jexcelapi/files/jexcelapi/2.6.12/

You can also get demo example inside this zipped file for JXL, as the extracted contents below show.

Extracted JXL archive showing the jar, documentation and demo folders

Some of the features:

  • JXL is able to read Excel file in Selenium for 95, 97, 2000, XP, 2003 workbook.
  • We can work with English, French, Spanish, German.
  • Copying a Chart and image insertion in Excel is possible

Drawback:

  • We can write Excel 97 and later only (writing in Excel 95 is not supported).
  • JXL does not support XLSX format of excel file.
  • It Generates spreadsheet in Excel 2000 format.

FAQs

Declare poi-ooxml, not poi alone. It pulls poi in transitively and supplies the XSSF classes XLSX needs. 5.5.1 is current.

The OOXML side of POI is missing or mismatched. Add poi-ooxml and keep every POI artifact on one version, since mixed releases leave schema classes off the path.

getStringCellValue only works on text cells. Use DataFormatter to read any cell as a string, or check getCellType and call FormulaEvaluator on formulas.

A missing row or cell returns null, so the loop throws NullPointerException. Test for null or CellType.BLANK first, or set a MissingCellPolicy so blanks return empty cells.

Machine learning models generate realistic rows, flag duplicates, and rank which combinations best expose defects, trimming bloated data driven testing sheets.

GitHub Copilot drafts reader and writer boilerplate from a comment. Review it, because it often suggests deprecated cell-type constants from older POI releases.

SXSSFWorkbook streams rows to disk instead of holding the workbook in memory, so large exports stop throwing OutOfMemoryError. When reading, handle rows inside the loop.

Keep it under src/test/resources and build the path from System.getProperty(“user.dir”). Absolute paths break once the suite runs elsewhere or on a Jenkins agent.

Summarize this post with: