Skip to content

Working with Excel - openpyxl Basics

What openpyxl is

openpyxlopenpyxl lets you work with .xlsx.xlsx files:

  • create workbooks
  • read/write cells
  • adjust styles

Create a workbook

excel_create.py
from openpyxl import Workbook
 
wb = Workbook()
ws = wb.active
ws.title = "Report"
 
ws["A1"] = "Name"
ws["B1"] = "Score"
 
ws.append(["Alice", 95])
ws.append(["Bob", 88])
 
wb.save("report.xlsx")
excel_create.py
from openpyxl import Workbook
 
wb = Workbook()
ws = wb.active
ws.title = "Report"
 
ws["A1"] = "Name"
ws["B1"] = "Score"
 
ws.append(["Alice", 95])
ws.append(["Bob", 88])
 
wb.save("report.xlsx")

Read an existing workbook

excel_read.py
from openpyxl import load_workbook
 
wb = load_workbook("report.xlsx")
ws = wb["Report"]
 
print(ws["A2"].value, ws["B2"].value)
excel_read.py
from openpyxl import load_workbook
 
wb = load_workbook("report.xlsx")
ws = wb["Report"]
 
print(ws["A2"].value, ws["B2"].value)

Tips

  • Keep a template .xlsx.xlsx if you need complex formatting
  • For CSV, prefer the csvcsv module or pandas

๐Ÿงช Try It Yourself

Exercise 1 โ€“ List Files with os.listdir

Exercise 2 โ€“ Join Paths with os.path.join

Exercise 3 โ€“ Write and Read a File

If this helped you, consider buying me a coffee โ˜•

Buy me a coffee

Was this page helpful?

Let us know how we did