4 Practical Python Programs for Working with Excel using the openpyxl Library
2 min readSep 12, 2024
pip install openpyxl
1. Creating a New Excel Workbook
import openpyxl
# Create a new workbook
wb = openpyxl.Workbook()
ws = wb.active
# Add data to the workbook
ws['A1'] = "Name"
ws['B1'] = "Age"
ws.append(['John', 28])
ws.append(['Jane', 25])
# Save the workbook
wb.save('clcoding.xlsx')
2. Reading Data from an Excel File
import openpyxl
# Load an existing workbook
wb = openpyxl.load_workbook('clcoding.xlsx')
ws = wb.active
# Read data from the workbook
for row in ws.iter_rows(values_only=True):
print(row)
('Name', 'Age')
('John', 28)
('Jane', 25)
3. Modifying an Existing Excel File
import openpyxl
# Load an existing workbook
wb = openpyxl.load_workbook('clcoding.xlsx')
ws = wb.active
# Modify a cell's value
ws['B2'] = 30
# Save the workbook with the…