How to read cell value in openpyxl in Python
In this openpyxl tutorial, we will learn how we can read the data from the cell of an Excel Sheet in Python.
The values that are stored in the cells of an Excel Sheet can be accessed easily using the openpyxl library. To read the cell values, we can use two methods, firstly the value can be accessed by its cell name, and secondly, we can access it by using the cell() function.
Program to read cell value using openpyxl Library in Python
Let’s understand it with an example:
Here, we took an Excel file having some values in its cells. We will access and read these values in our Python program using the openpyxl library.
Step1: Import the openpyxl library to the Python program.
import openpyxl
Step2: Load/Connect the Excel workbook to the program.
wb = openpyxl.load_workbook('filename.xlsx') #give the full path of the file here
Step3: Get the title of the default first worksheet of the Workbook.
sh = wb.active
Step4: Create variables and initialize them with the cell names.
c1 = sh['A1'] c2 = sh['B2']
Or
We can also read the cell value by using the cell() function. The cell() function takes rows and columns as the parameter for the position of the cell.
c3 = sh.cell(row=2,column=1)
Step5: Finally, print the values of the cell to the screen.
print("Value of the Cell 1:",c1.value) print("Value of the Cell 2:",c2.value) print("Value of the Cell 3:",c3.value)
Here is the complete program:
import openpyxl wb = openpyxl.load_workbook("//home//codespeedy//Documents//Book2.xlsx") sh = wb.active c1 = sh['A2'] c2 = sh['B2'] #Using cell() function c3 = sh.cell(row=3,column=3) print("Value of the Cell 1:",c1.value) print("Value of the Cell 2:",c2.value) print("Value of the Cell 3:",c3.value)
Output:
Value of the Cell 1: Sanam Value of the Cell 2: 21 Value of the Cell 3: 56000
Hope you have enjoyed this article and learned how to read the value of a cell of an Excel Workbook in Python.
You can also read, How to add color to Excel cells using Python
Leave a Reply