Python Excel Reading Operation (openpyxl Library)
Python Excel Reading Operation Using the openpyxl Library
I previously talked about reading an Excel file using the pandas library in Python. In this article, I wanted to talk about how to read an Excel file using another library called openpyxl.
Installation of the Required Library
pip install openpyxl or pip3 install openpyxl
Since pip is recognized as python 2 on most systems, you may get an error. If you do, try using pip3.
Including the Library in the Project
from openpyxl import load_workbook
We import openpyxl at the top of our Python project, and it is now completely ready to use.
Reading Operation
def read_excel(folder):
print("Excel file is being read..")
wb = load_workbook(folder + '.xlsx')
sheet = wb['Sheet1']
recipientNames = [cell.value for cell in sheet['A'][1:]]
recipientEmails = [cell.value for cell in sheet['B'][1:]]
data = list(zip(recipientNames, recipientEmails))
return data
We created a function called read_excel and turned the information we read with this function into a list and returned it from the function, thus allowing us to use the read data wherever we want.
Here, while reading, the part that says 'Sheet1' must be the name of our sheet, and just below it,
in the section [cell.value for cell in sheet['A']] the 'A' part is for the column you want to read.
For example, A is the 1st column, B the 2nd column, and so on.
The [1:] part after ['A'] indicates from which row to start. Note that it starts from 0, so if row 1 contains headers, entering 1 will skip the headers. If you want to include the headers, you can leave it as [:].
If you only want to take a certain range, you can use something like [2:5].
If you want to use the function in the example above
for data in read_excel("ExcelName"):print("Name" + data[0] + "E-Mail" + data[1])
It will be sufficient to call the command as shown above.


Yorum Gönder