Python Intermediate Lesson 7: Formatted Excel Reports With openpyxl

Python Intermediate Lesson 7: Formatted Excel Reports With openpyxl 1

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

⏱ 2 min read

πŸ“˜ Python Intermediate Course Β· Lesson 7 of 10

Advertisement
In this article
  1. A summary sheet with SUMIFS and a chart
  2. Common mistakes
  3. Practice

pandas’ to_excel dumps data. openpyxl lets you build a finished report: formatting, formulas that keep working when someone edits a number, and charts.

from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill
from openpyxl.chart import BarChart, Reference

wb = Workbook(); ws = wb.active; ws.title = "Sales"
ws.append(["Invoice", "Date", "Code", "Qty", "Rate", "Amount", "GST"])
for i, r in enumerate(rows, start=2):
    ws.append([r["invoice"], r["date"], r["code"], int(r["qty"]), price,
               f"=D{i}*E{i}", f"=ROUND(F{i}*{gst},2)"])        # live Excel formulas
for c in ws[1]:
    c.font = Font(bold=True, color="FFFFFF"); c.fill = PatternFill("solid", fgColor="217346")
for c in ws["F"][1:]: c.number_format = "#,##0.00"
ws.freeze_panes = "A2"

A summary sheet with SUMIFS and a chart

s = wb.create_sheet("Summary")
s.append(["Code", "Product", "Amount"])
s.append(["P104", "USB mouse", "=SUMIFS(Sales!F:F,Sales!C:C,A2)"])
chart = BarChart(); chart.add_data(Reference(s, min_col=3, min_row=1, max_row=7), titles_from_data=True)
s.add_chart(chart, "E2")
wb.save("output/sales-report.xlsx")
πŸ’‘ openpyxl writes formulas but doesn’t calculate them; Excel does when the file opens. If another program must read the totals, calculate them in Python and write the values.

Common mistakes

  • Saving over a file that’s open in Excel: PermissionError. Close it, or save under a new name with a timestamp.
  • Dates as text: write datetime.date objects and set number_format = "dd-mmm-yyyy".

Practice

Unzip the practice data into a folder, put this lesson’s script in the same folder and run it (python pyi-NN.py). Compare with the expected output file. Then change one thing (a filter, a column, a format) and predict the new output before you run it.

πŸ“Ž Practice files for this article

⬇ Download all 3 files (ZIP Β· 5 KB)

  • 🐍
    Lesson 7 scriptThe complete script from this lesson, ready to run.
    ⬇ PY Β· 2 KB
  • πŸ“„
    Expected outputWhat the script printed when we ran it, to compare with yours.
    ⬇ TXT Β· 186 B
  • πŸ—‚οΈ
    Practice data (zip)sales.csv (120 invoices, 2 deliberately broken rows), customers.csv, products.json, statement.txt, rates.json and 3 monthly CSVs.
    ⬇ ZIP Β· 4 KB

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

Leave a Reply

Your email address will not be published. Required fields are marked *