Python Lesson 11: Excel Files With openpyxl

πŸ“Ž This article includes 3 downloadable practice files ↓

⏱ 2 min read

πŸ“˜ Python Beginner Course Β· Lesson 11 of 12

In this article
  1. Step 1: write data with pandas
  2. Step 2: format with openpyxl
  3. Step 3: formulas and a chart
  4. Reading cells
  5. What openpyxl can’t do
  6. Where beginners go wrong
  7. Practice

pandas writes data to Excel; openpyxl makes it look like a report: bold coloured headers, number formats, column widths, formulas and charts. Together they produce a file your manager can open without knowing Python exists.

Step 1: write data with pandas

import pandas as pd
summary = df.groupby("region", as_index=False)["amount"].sum()
with pd.ExcelWriter("region_report.xlsx") as xw:
    summary.to_excel(xw, sheet_name="Summary", index=False)
    df.to_excel(xw, sheet_name="Data", index=False)

Step 2: format with openpyxl

from openpyxl import load_workbook
from openpyxl.styles import Font, PatternFill
wb = load_workbook("region_report.xlsx")
ws = wb["Summary"]
for c in ws[1]:                                   # header row
    c.font = Font(bold=True, color="FFFFFF")
    c.fill = PatternFill("solid", fgColor="1F6F43")
for c in ws["B"][1:]:                             # column B except the header
    c.number_format = "#,##0"
ws.column_dimensions["A"].width = 12

For Indian grouping in the Excel file itself, use the number format ##,##,##0.

Step 3: formulas and a chart

from openpyxl.chart import BarChart, Reference
n = ws.max_row
ws.append(["Total", f"=SUM(B2:B{n})"])            # a real Excel formula
ch = BarChart(); ch.title = "Sales by region"
ch.add_data(Reference(ws, min_col=2, min_row=1, max_row=n), titles_from_data=True)
ch.set_categories(Reference(ws, min_col=1, min_row=2, max_row=n))
ws.add_chart(ch, "D2")
wb.save("region_report.xlsx")
πŸ’‘ openpyxl writes formulas but doesn’t calculate them; Excel calculates when the file opens. If you need the value inside Python, calculate it with pandas instead.

Reading cells

wb = load_workbook("input.xlsx", data_only=True)   # data_only=True reads cached values, not formulas
ws = wb.active
ws["B2"].value
for row in ws.iter_rows(min_row=2, values_only=True):
    print(row)

What openpyxl can’t do

It can’t run VBA macros, refresh pivots or Power Query, or calculate formulas. For .xlsb files use pyxlsb (read-only); to drive Excel itself on Windows, xlwings is the tool.

Where beginners go wrong

Problem Cause
PermissionError when saving The file is open in Excel
Formulas read as text “=SUM(…)” Use data_only=True to read results (the file must have been saved by Excel)
Formatting lost Writing with pandas again after formatting overwrites it; format last

Practice

Download the script (and data file, if listed) below into one folder. Open a terminal in that folder and run python lesson-NN.py. Compare with the expected output, then change something and run it again: that’s how Python is learned.

πŸ“Ž Practice files for this article

Free to use for learning. Files with macros (.bas) are plain text β€” import them with Alt+F11 β†’ File β†’ Import File, and always test on a copy.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free Β· AI can be wrong