How can we read data from an excel sheet in Selenium Webdriver?

SeleniumAutomation TestingTesting Tools

We can read data from an excel sheet in Selenium webdriver in Python.

An excel workbook consists of multiple sheets and each sheet consists of cells and columns.

To work with excel in Python(with extension .xlsx, .xlsm, and so on) we have to utilize the OpenPyXL library. To install this package, we have to run the command: pip install openpyxl. Also, we have to add the statement import openpyxl in our code.

To open an excel workbook, the method is load_workbook and pass the path of the excel file as a parameter to this method. To identify the active sheet, we have to use the active method on the workbook object.

To read a cell, the method cell is applied on the active sheet and the row and column numbers are passed as parameters to this method. Then the value method is applied on a particular cell to read values within it.

Let us read the value at the third row and second column having the value D as shown below in an excel workbook of name Data.xlsx −

Example

import openpyxl
#configure workbook path
b = openpyxl.load_workbook("C:\\Data.xlsx")
#get active sheet
sht = b.active
#get cell address within active sheet
cl = sht.cell (row = 3, column = 2)
#read value with cell
print("Reading value from row-3, col-2: ")
print (cl.value)

Output

raja
Published on 08-Apr-2021 07:46:19
Advertisements