Examples of openpyxl Library Usage in Python for Excel Automation

21 Jan 2026

๐Ÿ“˜ Introduction to openpyxl

The openpyxl library in Python is used to read, write and modify Excel (.xlsx) files.

It is widely used in:

  • Excel Automation
  • Report generation
  • Data entry systems
  • Office automation projects

๐Ÿ”ง Install openpyxl

pip install openpyxl

๐Ÿ“‚ Example 1: Create a New Excel File

from openpyxl import Workbook

wb = Workbook()
ws = wb.active
ws.title = "Students"

ws['A1'] = "Name"
ws['B1'] = "Marks"

wb.save("students.xlsx")

๐Ÿ‘‰ This creates a new Excel file with headers.


๐Ÿ“„ Example 2: Write Data into Excel

from openpyxl import Workbook

wb = Workbook()
ws = wb.active

ws.append(["Name", "Marks"])
ws.append(["Ravi", 85])
ws.append(["Anitha", 92])
ws.append(["Kumar", 78])

wb.save("marks.xlsx")

๐Ÿ‘‰ Automatically inserts multiple rows.


๐Ÿ“– Example 3: Read Data from Excel

from openpyxl import load_workbook

wb = load_workbook("marks.xlsx")
ws = wb.active

for row in ws.iter_rows(values_only=True):
    print(row)

๐Ÿ‘‰ Reads all rows from Excel file.


โœ๏ธ Example 4: Update Existing Excel File

from openpyxl import load_workbook

wb = load_workbook("marks.xlsx")
ws = wb.active

ws['B2'] = 90   # Change Ravi's marks
wb.save("marks.xlsx")

๐Ÿ‘‰ Updates specific cell value.


๐Ÿ“Š Example 5: Find Maximum Marks

from openpyxl import load_workbook

wb = load_workbook("marks.xlsx")
ws = wb.active

marks = []
for row in ws.iter_rows(min_row=2, min_col=2, values_only=True):
    marks.append(row[0])

print("Maximum Marks:", max(marks))

๐Ÿ‘‰ Useful for result analysis.


๐Ÿงพ Example 6: Apply Formatting

from openpyxl import load_workbook
from openpyxl.styles import Font

wb = load_workbook("marks.xlsx")
ws = wb.active

ws['A1'].font = Font(bold=True)
ws['B1'].font = Font(bold=True)

wb.save("marks.xlsx")

๐Ÿ‘‰ Makes headers bold.


๐Ÿง  Why openpyxl is Important for Automation?

โœ” Automates Excel work

โœ” Saves time

โœ” Reduces manual errors

โœ” Used in office reports

โœ” Useful for data analysis

โœ” Highly demanded in Python jobs

๐ŸŽฏ Student-Friendly Summary

Manual WorkUsing openpyxlOpen Excel manuallyPython opens ExcelType data manuallyPython writes dataCalculate by handPython calculatesTime consumingFast & automatic

๐Ÿš€ Conclusion

The openpyxl library makes Excel automation easy and powerful in Python.

If you want to build:

  • Report automation
  • Excel based projects
  • Office automation tools

Then learning openpyxl is must for you!