Python Openpyxl Read Excel File Example

By Hardik Savani October 30, 2023 Category : Python

Hi Dev,

In this example, I will show you python read excel file openpyxl. We will look at an example of python read xls file openpyxl. step by step explain how to read excel file in python using openpyxl. I explained simply about python openpyxl read excel file.

In this example, we will read excel file using python openpyxl module. we will use load_workbook() function to read excel file date using python openpyxl. so let's see a simple example.

You can use these examples with python3 (Python 3) version.

If you haven't install openpyxl in your system then you can install using the below command:

pip install openpyxl

Example 1:

I simply created data.xlsx file with content as like below, we will use same file for both example:

demo.xlsx

main.py

import openpyxl
  
# Define variable to load the dataframe
dataframe = openpyxl.load_workbook("demo.xlsx")
   
# Define variable to read sheet
data = dataframe.active
   
# Display Row Data
for row in range(0, data.max_row):
    for col in data.iter_cols(1, data.max_column):
        print(col[row].value)

Output:

ID
Name
Email
1
Hardik Savani
hardik@gmail.com
2
Vimal Kashiyani
vimal@gmail.com
3
Harshad Pathak
harshad@gmail.com

Example 2: Read Excel file with Multiple Sheets

I simply created data.xlsx file with SheetOne and SheetTwo as like below, we will use same file for both example:

demo.xlsx: SheetOne

demo.xlsx: SheetTwo

main.py

import openpyxl
   
# Define variable to load the dataframe
dataframe = openpyxl.load_workbook("demo.xlsx")
  
# Read SheetOne
sheetOne = dataframe['SheetOne']
   
# Iterate the loop to read the cell values
for row in range(0, sheetOne.max_row):
    for col in sheetOne.iter_cols(1, sheetOne.max_column):
        print(col[row].value)
   
# Read SheetTwo
sheetTwo = dataframe['SheetTwo']
   
# Iterate the loop to read the cell values
for row in range(0, sheetTwo.max_row):
    for col in sheetTwo.iter_cols(1, sheetTwo.max_column):
        print(col[row].value)

Output:

ID
Name
Email
1
Hardik Savani
hardik@gmail.com
2
Vimal Kashiyani
vimal@gmail.com
3
Harshad Pathak
harshad@gmail.com
      
ID
Name
1
Hardik
2
Vimal
3
Harshad

I hope it can help you...

Tags :
Shares