How to Read Data from Excel File Using Openpyxl in Python?
Share
Condition for Read the Data from Excel File Using Openpyxl in Python
Description:
Openpyxl is a Python library used to read, write, and manipulate Excel files in the .xlsx format.
Step-by-Step Process
Install the Library:
Install the openpyxl library using pip install openpyxl.
Load the Excel Workbook:
Open the Excel file using openpyxl.load_workbook().
Select a Sheet:
Select the active sheet or a specific sheet where the data resides.
Read Data:
Use the .cell() method or iterate through rows/columns to extract data.
Close the Workbook:
After reading data, close the workbook to release resources.
Sample Code
import openpyxl
#Load the Excel workbook
workbook = openpyxl.load_workbook("iris_data.xlsx")
#Select the active sheet or a specific sheet
sheet = workbook.active # You can also use workbook["SheetName"] to select a specific sheet
#Read data from a specific cell (example: A1)
data = sheet["A1"].value
print(f"Data in cell A1: {data}")
#Iterate through rows and columns to read all data
print("All data in the sheet:")
for row in sheet.iter_rows(values_only=True):
print(row)
#Close the workbook
workbook.close()