All about excel in selenium

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)
  • Classes and Interfaces in POI
  • Read/Write operation
  • Read data from Excel file
  • Write data on Excel file
  • Excel Manipulation using JXL API

Exporting Excel

How to handle excel file using POI (Maven POM Dependency)

How to export Excel File in Selenium Webdriver using Aapache POI

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

How to export Excel File in Selenium Webdriver using Aapache POI

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

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

How to download Apache POI

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.

How to download Apache POI

Classes and Interfaces in POI:

Classes and Interfaces in Apache POI

Classes and Interfaces in Apache POI

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

  • 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

Read/Write Data from Excel File in Selenium Webdriver

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.

Read/Write Data from Excel File in Selenium Webdriver

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);

    }

}

Read/Write Data from Excel File in Selenium Webdriver

Excel Manipulation using JXL API

How to manipulate Excel File 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.

TIPS: My suggestion is not to use JXL in any new project because the library is not in active development from 2010 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/

How to manipulate Excel File using JXL API

You can also get demo example inside this zipped file for JXL.

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.

Summary:

  • Excel file can be read by Java IO operation. For that, we need to use Apache POI Jar.
  • There are two kinds of a workbook in Excel file, XLSX and XLS files.
  • POI has different Interfaces Workbook, Sheet, Row, Cell.
  • These interfaces are implemented by corresponding XLS (HSSFWorkbook, HSSFSheet, HSSFRow, HSSFCell) and XLSX (XSSFWorkbook, XSSFSheet, XSSFRow, XSSFCell) file manipulation classes.
  • JXL is another API for Excel handling in Selenium.
  • JXL cannot work with XLSX format of excel.

Automation testers have to automate a large number of end-user actions to monitor, evaluate and verify website functionality. Essentially, they must observe how a site behaves when users interact with its various features and offerings. This article will focus on how to automate one such user action – how to read data from an Excel file in Selenium WebDriver using Java.

Selenium is a widely used automation testing tool for browser automation. The Java programming language provides different classes or interfaces to perform file manipulation actions.

Apache POI libraries are used to perform such operations. Some of the interfaces to read or write data from external resources are given below:

  1. POIFS (Poor Obfuscation Implementation File System)
  2. HSSF (Horrible Spreadsheet Format)
  3. XSSF (XML Spreadsheet Format)
  4. HPSF (Horrible Property Set Format)
  5. HWPF (Horrible Word Processor Format)
  6. XWPF (XML Word Processor Format)
  7. HSLF (Horrible Slide Layout Format)
  8. HGDF (Horrible Diagram Format)
  9. HDBF (Horrible PuBlisher Format)

What is Apache POI?

Apache POI is an open-source Java library often utilized to create and handle Microsoft Office-based files. Users can leverage POI to perform various operations (modify, create, display, read) on specific file formats (Excel files being one of them). Since Java does not offer built-in support for Excel files, testers need open-source APIs to work with them. Apache POI provides a Java API that lets users operate and maneuver file formats built on the Office Open XML (OOXML) standard and Microsoft’s OLE2 standard.

To create or maintain Excel Workbooks, Apache POI provides a ”Workbook” as a super-interface of all classes. It belongs to org.apache.poi.ss.usermodel package. It uses WorkbookFactory class to create the appropriate workbook (i.e. HSSFWorkbook or XSSFWorkbook). The two classes which implement the “Workbook” interface are given below:

  • HSSFWorkbook– Methods of this class are used to read or write data to Microsoft Excel file in .xls format.
  • XSSFWorkbook– Methods of this class are used to read/write data to Microsoft Excel and OpenOffice XML files in .xls or .xlsx format.

Now let’s understand how to configure apache POI Selenium in the system.

Apache POI Installation

Step 1– Download the Apache POI jar file from the official website and click on the Download section. One can download the
Binary Distribution zip file.
Download Apache POI

Step 2 – Once the zip file is downloaded, extract it and save it.
Step 3 – Configure the build path in Eclipse and add all the POI external jars listed below.
Once all the Jar files are added, the user can read and write the data from and to Excel files.Apache POI Selenium - JAR Files

Read Data from Excel File in Selenium

The code below is used to read the data from the sample Excel sheet in Selenium. This is the excel sheet data that will be used for reading data in this example.
Reading data from excel - output

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class BrowserStackReadExcelTest {
public static void main (String [] args) throws IOException{
//Path of the excel file
FileInputStream fs = new FileInputStream("D:\DemoFile.xlsx");
//Creating a workbook
XSSFWorkbook workbook = new XSSFWorkbook(fs);
XSSFSheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
System.out.println(sheet.getRow(0).getCell(0));
Row row1 = sheet.getRow(1);
Cell cell1 = row1.getCell(1);
System.out.println(sheet.getRow(0).getCell(1));
Row row2 = sheet.getRow(1);
Cell cell2 = row2.getCell(1);
System.out.println(sheet.getRow(1).getCell(0));
Row row3 = sheet.getRow(1);
Cell cell3 = row3.getCell(1);
System.out.println(sheet.getRow(1).getCell(1));
//String cellval = cell.getStringCellValue();
//System.out.println(cellval);
}
}

In the code, based on the cell and row values, the data will be read and retrieved from the Excel files. Now let’s understand how to write data into the Excel file.

Run Selenium Tests

Write Data into Excel File in Selenium

The code below is used to write data into an Excel file in Selenium.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.openqa.selenium.remote.DesiredCapabilities;
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 WriteintoExcel {
public static void main(String[] args) throws IOException {
String path = "D://DemoFile.xlsx";
FileInputStream fs = new FileInputStream(path);
Workbook wb = new XSSFWorkbook(fs);
Sheet sheet1 = wb.getSheetAt(0);
int lastRow = sheet1.getLastRowNum();
for(int i=0; i<=lastRow; i++){
Row row = sheet1.getRow(i);
Cell cell = row.createCell(2);

cell.setCellValue("WriteintoExcel");

}

FileOutputStream fos = new FileOutputStream(path);
wb.write(fos);
fos.close();
}

}

In the code below, based on the cell value WriteintoExcel, data will be written as depicted below.

This is how to read Excel files in Selenium WebDriver using Apache POI. Given how popular Excel sheets are for data cataloging and display, knowing how to handle Excel in Selenium is a valuable skill for testers.  Since automation testing must cover as many user scenarios as possible, it is important to know how to code and execute those scenarios quickly and accurately. This article aims to add to a Selenium tester’s skillset by demonstrating how to read data from Excel in Selenium WebDriver using POI libraries.

You are here: Home / Advance Selenium / How to Read and Write excel files in Selenium using Apache POI

Excel-Reading in Selenium

Hello, Welcome to Selenium tutorial, in this post, we will see how to Read and Write excel files in Selenium

Selenium support only Web browser automation so for Read and Write excel files in Selenium we have to take help of third party API like JExcel and Apache POI

Apache POI is an API, which is freeware and written in Java and gives so much flexibility to read/write files it has so many predefined methods, classes, and interfaces.

Once you move to next step like designing framework then you must be familiar with excel file. We have to use this concept while designing Data Driven Framework as well.

Another point this is one of the most important questions in interviews as well and you should be having complete knowledge of it.

Read and Write excel files in Selenium

Step 1- Download apache poi jar file as below

Go to Official website of Apache POI and Click on the download section

http://poi.apache.org/download.html

Read and Write excel files in Selenium

Read/Write Excel file in Selenium

Now Click on the below mention link

Read and Write excel files in Selenium

Read/Write Excel file in Selenium

All jar files will come in zip files, Extract it and you will get final jar folder looks like this

Read/Write excel files in Selenium

Read/Write Excel file in Selenium

Add all jar files or below mention, jar files into Project.

Read/Write excel files in Selenium

Read/Write Excel file in Selenium

Step 2- How to add Jar files

Select project then Right click on project > Build path > Configure build path > Click on lib section > Add external jar
Precondition- Create a xlsx file and enter some data to read and save file at particular location.

Read Excel file using Apache POI

In below example, I am reading simple .xlsx file

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.Test;


public class ReadandWriteExcel {

 public static void main(String []args){
  
  try {
  // Specify the path of file
  File src=new File("filepath/excelsheetname.xlsx");

   // load file
   FileInputStream fis=new FileInputStream(src);
 
   // Load workbook
   XSSFWorkbook wb=new XSSFWorkbook(fis);
   
   // Load sheet- Here we are loading first sheetonly
      XSSFSheet sh1= wb.getSheetAt(0);
 
  // getRow() specify which row we want to read.

  // and getCell() specify which column to read.
  // getStringCellValue() specify that we are reading String data.


 System.out.println(sh1.getRow(0).getCell(0).getStringCellValue());

 System.out.println(sh1.getRow(0).getCell(1).getStringCellValue());

 System.out.println(sh1.getRow(1).getCell(0).getStringCellValue());

 System.out.println(sh1.getRow(1).getCell(1).getStringCellValue());

 System.out.println(sh1.getRow(2).getCell(0).getStringCellValue());

 System.out.println(sh1.getRow(2).getCell(1).getStringCellValue());
 
  } catch (Exception e) {

   System.out.println(e.getMessage());

  }
  
 }
 
}

Write Excel file Selenium Webdriver

Now if you are familiar with reading excel then it is just a cup of tea now

In below example, I am  writing .xlsx file

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

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

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

import org.testng.annotations.Test;

public class ReadandWriteExcel {

 public static void main(String []args){

  try {

  // Specify the file path which you want to create or write

  File src=new File("./testdata/test.xlsx");

  // Load the file

  FileInputStream fis=new FileInputStream(src);

   // load the workbook

   XSSFWorkbook wb=new XSSFWorkbook(fis);

  // get the sheet which you want to modify or create

   XSSFSheet sh1= wb.getSheetAt(0);

 // getRow specify which row we want to read and getCell which column

 System.out.println(sh1.getRow(0).getCell(0).getStringCellValue());

 System.out.println(sh1.getRow(0).getCell(1).getStringCellValue());

 System.out.println(sh1.getRow(1).getCell(0).getStringCellValue());

 System.out.println(sh1.getRow(1).getCell(1).getStringCellValue());

 System.out.println(sh1.getRow(2).getCell(0).getStringCellValue());

 System.out.println(sh1.getRow(2).getCell(1).getStringCellValue());

// here createCell will create column

// and setCellvalue will set the value

 sh1.getRow(0).createCell(2).setCellValue("2.41.0");

 sh1.getRow(1).createCell(2).setCellValue("2.5");

 sh1.getRow(2).createCell(2).setCellValue("2.39");


// here we need to specify where you want to save file

 FileOutputStream fout=new FileOutputStream(new File("location of file/filename.xlsx"));


// finally write content 

 wb.write(fout);

// close the file

 fout.close();

  } catch (Exception e) {

   System.out.println(e.getMessage());

  }

 }

}

Some companies also use CSV files to store the data and some also use Databases to store the data so based on your requirement you can select any data source.

I hope you have enjoyed the article if yes then share with your friends and colleagues as well.

Please comment in below section if you are facing any issue. Thanks For visiting my blog keep in touch

Reader Interactions

In the previous articles on Selenium Python Tutorial, we have covered “Handling Cookies in Selenium Python“. In this tutorial, we will learn Working with excel in Selenium Python. 

We can work with the excel workbook in Selenium WebDriver. Excel, also called a spreadsheet can have extensions like .xlsx, .xlsm, and so on. Excel consists of multiple worksheets.

Each worksheet is divided into rows and columns both having an address. The address of rows starts from 1 and the column address begins from A. A cell inside a worksheet is the intersection point of a row and a column.

Each cell in a worksheet has a unique address defined by the combination of row and column address. Out of the multiple worksheets in a workbook, the worksheet on which we are currently working is known as the active worksheet.

While working with the Selenium tool along with language Python, we use the OpenPyXL library to access Excel from version 2010. Python does not provide this library automatically.

We need to run the command pip install openpyxl to get the OpenPyXL library. Also we have to add an import openpyxl statement in our code to get all the methods under that library.

To fetch the active worksheet in a workbook, we have to use the load_workbook () method which takes the path of the Excel as its parameter then uses the active method.

Code Implementation to identify active worksheet.

import openpyxl
# to load the workbook with its path
bk = openpyxl.load_workbook(“C:\STM\Python.xlsx”)
# to identify active worksheet
s = bk.active

To read the value of a particular cell, we need to follow all the above steps. Then we have to apply the cell () method on the active worksheet object. This method contains the row and column number as parameters. Finally we shall use the value method to actually read the cell data.

Code Implementation to read a cell value.

import openpyxl
# to load the workbook with its path
bk = openpyxl.load_workbook(“C:\STM\Python.xlsx”)
# to identify active worksheet
s = bk.active
# to identify the cell
c = s.cell (row = 3, column = 1)
# to retrieve the cell value and print
print ( c.value)

To write the value on a particular cell, we need to identify the active worksheet. Then we have to apply the cell () method on the active worksheet object. This method contains the row and column number as parameters.

Next, to set a value, we have to use the value method. Finally to save the workbook, we have to apply the save () method on the workbook object. The save () method takes the path of the file to be saved as a parameter.

Code Implementation to write a cell value.

import openpyxl
# to load the workbook with its path
bk = openpyxl.load_workbook(“C:\STM\Python.xlsx”)
# to identify active worksheet
s = bk.active
# to identify the cell
c = s.cell (row = 2, column = 8)
# to write a value in that cell
s.cell (row = 2, column = 8).value = "Python"
# to save the workbook in location
bk.save ("C:\STM\Python.xlsx")

To get the maximum number of rows and columns in the worksheet, we need to identify the active worksheet. Then we have to apply the max_row method on the active worksheet object to get the total occupied rows count. Also, we have to apply the max_column method on the active worksheet object to get the total occupied columns count.

Code Implementation to identify maximum occupied row and column count.

import openpyxl
# to load the workbook with its path
bk = openpyxl.load_workbook(“C:\STM\Python.xlsx”)
# to identify active worksheet
s = bk.active
# to identify maximum rows count
print ( s.max_row)
# to identify maximum columns count
print ( s.max_column)

To get all the cell data in the worksheet, we need to identify the active worksheet. Then we have to apply the max_row method on the active worksheet object to get the total occupied rows count. Also, we have to apply the max_column method on the active worksheet object to get the total occupied columns count.

To obtain the cell data, we shall then iterate through the maximum number of rows and columns that are occupied in the worksheet and then retrieve the cell value.

Code Implementation to get all the cell values in the worksheet.

import openpyxl
# to load the workbook with its path
bk = openpyxl.load_workbook(“C:\STM\Python.xlsx”)
# to identify active worksheet
s = bk.active
# to identify maximum rows count
print ( s.max_row)
# iterate till the count of occupied rows
for m in range ( 1, s.max_row + 1):
# iterate till the count of occupied columns
for n in range ( 1, s.max_column + 1):
# to get the cell data and print
print (s.cell (row=m, column=n). value) 

To get all the cell data of a particular row in the worksheet, we need to identify the active worksheet. Then we have to apply the max_row method on the active worksheet object to get the total occupied rows count. Also, we have to apply the max_column method on the active worksheet object to get the total occupied columns count.

To obtain the cell data, we shall then iterate through the maximum number of rows and columns that are occupied in the worksheet and then retrieve the cell value. Once we get the cell value we shall execute a conditional statement, and get all the values from a specific row which matches our requirement.

Excel Data In Selenium Python

Let us consider a workbook having a worksheet with the above set of data. Suppose we want to get the Student details for the topic Python.

Code Implementation for the above scenario.

import openpyxl
# to load the workbook with its path
bk = openpyxl.load_workbook(“C:\STM\Python.xlsx”)
# to identify active worksheet
s = bk.active
# to identify maximum rows count
print ( s.max_row)
# iterate till the count of occupied rows
for m in range ( 1, s.max_row + 1): 
# to get all the cell values from column 1
if s.cell (row=m, column=1).value == "Python" :
# iterate till the count of occupied columns
for n in range ( 1, s.max_column + 1):
# to get all the cell data from a row and print
print (s.cell (row=m, column=n). value) 

In the next article, we will learn 100+ Selenium Interview Questions.

Related posts:

  • Selenium Python Tutorial
  • Selenium Java Tutorial
  • Selenium Interview Questions
  • API Testing Tutorial
  • Postman Tutorial

Rajkumar SM is a founder of SoftwareTestingMaterial. He is a certified Software Test Engineer by profession and a blogger & a YouTuber by a choice. He has extensive experience in the field of Software Testing. Furthermore, he loves to be with his wife and a cute little kid ‘Freedom’.

Hello Friends, In this post we will see How to read write excel in Selenium using Apache POI.

We know  Selenium only support web application so to read write excel in selenium we need to take help of third party tool or API like Apache POI or JExcel.

Here we will use Apache POI API to read write excel in selenium.

What is Apache POI?

Apache POI is a Java API which is the collection of different java libraries which give us facility to read, write and manipulate different Microsoft files like excel sheet, word files, power-point etc.

Apache POI in Selenium

Apache POI in Selenium is used when we developed data driven framework then it is used to read write excel in Selenium. It provided a set of Interfaces and classes which are used to reading/writing test data from excel.

In below image we can see those interfaces and classes.

Classes and Interfaces in POI

Apache POI Interfacs and Classes

There are two type of excel file extension- .xls and .xlsx

Apache POI supports both type of excel file format.

Following is a list of POI libraries which have different Interfaces and Classes

Workbook: It is an interface which is implemented by HSSFWorkbook and XSSFWorkbook.

HSSFWorkbook: It is a class which implements Workbook interface and represents .xls file format.

XSSFWorkbook: It is a class which implements Workbook interface and represents .xlsx file format.

Sheet: It is an interface which is implemented by HSSFSheet and XSSFSheet.

HSSFSheet: It is a class which implements Sheet interface and represents sheet .xls file.

XSSFWorkbook: It is a class which implements Sheet interface and represents sheet in .xlsx file.

Row: It is an interface which is implemented by HSSFRow and XSSFRow.

HSSFRow: It is a class which implements Row interface and represents row in the sheet of  .xls file.

XSSFRow: It is a class which implements Row interface and represents row in the sheet of .xlsx file.

Cell: It is an interface which is implemented by HSSFCell and XSSFCell.

HSSFCell: It is a class which implements Cell interface and represents cell in the row  of  .xls file.

XSSFCell: It is a class which implements Row interface and represents cell in the row of .xlsx file.


Read Excel File Using For Loop in Selenium

There are different steps we need to follow.

Step-1:  Download apache POI jar files

Go to site of Apache POI and click on Download

Download Apache POI Jar file

Step-2:  Extract the ZIP file. See in below image. Import all jar files into your selenium project.

If you don’t know how to add jars in your selenium project. Refer below link.

Must Read: How to import Jar files in Selenium Project

Apache POI jars

Note: If you are using Maven project in your selenium framework then no need to follow step 2. You have to add maven dependency into your pom.xml file of maven project.

In below image you can see my excel file extension and excel data which I am going to read.

Code To Read Excel using For loop in Selenium

package exceloperations;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadData {
    
    public static void main(String[] args) throws IOException {
        
        
        String excelpath = ".\datafiles\EmployeeDetails.xlsx";
        FileInputStream inputstream = new FileInputStream(excelpath);
        
        
        XSSFWorkbook workbook = new XSSFWorkbook(inputstream);
        XSSFSheet sheet = workbook.getSheet("Employee");
        
        // Using for loop
        
        int rows = sheet.getLastRowNum();
        int cols= sheet.getRow(1).getLastCellNum();
        
        for(int r=0; r<rows; r++) {
            
            XSSFRow row=sheet.getRow(r);
            
            for(int c=0; c< cols; c++) {
                
                XSSFCell cell=row.getCell(c);
                switch(cell.getCellType())
                {
                case STRING: System.out.println(cell.getStringCellValue()); break;
                case NUMERIC: System.out.println(cell.getNumericCellValue()); break;
                case BOOLEAN: System.out.println(cell.getBooleanCellValue()); break;
                
                }
                
            }
            
            System.out.println();
        }
        
    }

}

Screenshot of above code:

Cod for How To Read and Write excel in Selenium


Code for Read Excel File using Iterator in Selenium

package exceloperations;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadDataIterator {
    
    public static void main(String[] args) throws IOException {
    
    String excelpath = ".\datafiles\EmployeeDetails.xlsx";
    FileInputStream inputstream = new FileInputStream(excelpath);
            
    XSSFWorkbook workbook = new XSSFWorkbook(inputstream);
    XSSFSheet sheet = workbook.getSheet("Employee");
    
    //// Using Iterator method
    
    Iterator iterator = sheet.iterator();
    
    while(iterator.hasNext()){
        
        XSSFRow row =(XSSFRow)iterator.next();
        
        Iterator cellIterator= row.cellIterator();
        
        while(cellIterator.hasNext()) {
            
            XSSFCell cell= (XSSFCell)cellIterator.next();
            
            switch(cell.getCellType())
            {
            case STRING: System.out.println(cell.getStringCellValue()); break;
            case NUMERIC: System.out.println(cell.getNumericCellValue()); break;
            case BOOLEAN: System.out.println(cell.getBooleanCellValue()); break;
            
            }
            System.out.println();
        }
        
    }

}

}



How To Write data into Excel sheet in Selenium

Before writing data in excel we need to create a new workbook, then create a sheet then create rows inside the sheet and create cell in each rows.

So structure is like this-

Workbook –>Sheet –> Row –> Cell

Before writing some data into excel we need to prepare data those we are going to write. So here we are using Java collection to store the data and same data we will write into excel sheet.

Code for Write data into Excel in Selenium

package exceloperations;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class WriteDataExcelFile {
    
    public static void main(String[] args) {
        
        
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("Emp Info");
        
        Object empdata[][] = {  {"Emp ID", "Name", "Job"},
                                {101, "Ajeet", "Engineer"},
                                {102, "Amit", "Lead"},
                                {103,"Kedar", "Manager"}
                                        
                             };
        
        // Now Above data we will write into excel sheet
        
        //Using for loop
        int rows = empdata.length;
        int cells = empdata[0].length;
        
        System.out.println(rows);  //4
        System.out.println(cells); //3
        
        for(int r=0; r<rows; r++) {
            
            XSSFRow row=sheet.createRow(r);
            
            for(int c=0; c<cells; c++) {
                
                XSSFCell cell=row.createCell(c);
                Object value=empdata[r];
                
                if(value instanceof String) {
                    cell.setCellValue((String)value);
                    

                if(value instanceof Integer) {
                    cell.setCellValue((Integer)value);
                        

                if(value instanceof Boolean) {
                    cell.setCellValue((Boolean)value);
                        
                    
                }
                
            }
            
        }
        
    }

}

Code Explanation:

  1. We have created an empty workbook. Then created a sheet using createSheet() inside the workbook.
  2. We have written all data into Object two dimensional array which we want to write into excel.
  3. We have created multiple rows and columns using createRow() and createCell() method in the sheet.
  4. Now using for loop we have fetched all object array data. instanceof is known as comparison operator which is used to compare object type. Its return either true or false.
  5. Create a filepath and open an outputstream to write the data into excel. Write the workbook into file system.
  6. Close the outputstream.
  7. Print data writing is successful.

Summary

I hope you enjoyed this tutorial and learnt something new.

Final word, Bookmark this post  “How to read write excel in Selenium” for future reference.

If you have other questions or feedback, the comment section is yours. Don’t forget to leave a comment below!

Like this post? Please share to your friends:
  • All about excel functions
  • All about excel forms
  • All about excel conditional formatting
  • All about excel charts
  • All 50 states word search