๐ 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!