Data analysis · Intermediate · 22 min
Automate a monthly Excel report with Python
By Padding · Updated 18 Nov 2026
Python 3.15 · pandas 3.1.1 · XlsxWriter 3.3.4 · openpyxl 3.1.5 · uv 0.13 (checked on python:3.15-slim)
You will replace a copy-and-paste monthly report with one command that checks each branch's CSV file, builds a summary in pandas 3.1 and writes a formatted Excel workbook with a native chart, named by month.
On this page
Every month someone downloads a CSV from each branch, pastes them into one workbook, fixes the column that came out as text, rebuilds the pivot table, nudges the chart range and saves the file as Report FINAL v2.xlsx. It takes an afternoon, and the mistakes are quiet: a branch file that never arrived, a renamed column, last month's rows left in by accident.
This tutorial turns that job into one command. A trading company with branches in Lagos, Nairobi, Accra and Kampala sends one CSV per branch each month. Your script reads that month's folder, refuses to continue if a file is missing or malformed, builds a summary with pandas, and writes a workbook with XlsxWriter: a formatted summary sheet with a native Excel chart, a data sheet with every order, frozen headers, and a file name that carries the month. Last, you read the workbook back from Python to prove it holds what you meant.
The code is split into four small files, one per job, so each part can be checked on its own:
checks.pyloads and checks the branch filessummary.pybuilds the summary tableworkbook.pywrites the Excel filereport.pyis the command you run
Step 1 · Create the project
Make a demo folder and add the three libraries. pandas does the analysis, XlsxWriter writes .xlsx files with formats and charts, and openpyxl reads .xlsx files back, which pandas also uses for read_excel. The ranges allow patch releases and nothing newer:
mkdir -p ~/branch-report-demo
cd ~/branch-report-demo
uv init --no-package
rm -f main.py
uv add "pandas>=3.1,<3.2" "xlsxwriter>=3.3,<3.4" "openpyxl>=3.1,<3.2"uv init also writes a starter main.py, which this project does not use, so the second-last line removes it.
Check it worked
uv run python -c "import pandas, xlsxwriter, openpyxl; print(pandas.__version__, xlsxwriter.__version__, openpyxl.__version__)"The output is 3.1.1 3.3.4 3.1.5, or later patch releases of each.
Step 2 · Put this month's branch files in a folder
The report expects one folder per month under incoming/, named YYYY-MM, with one CSV per branch named after the branch. Every file has the same five columns. Create October 2026:
mkdir -p incoming/2026-10
cat > incoming/2026-10/lagos.csv <<'CSV'
order_id,date,product,quantity,unit_price
L-1001,2026-10-02,Notebook,10,2.50
L-1002,2026-10-09,Printer ink,2,18.00
L-1003,2026-10-21,Desk lamp,1,24.00
CSV
cat > incoming/2026-10/nairobi.csv <<'CSV'
order_id,date,product,quantity,unit_price
N-2001,2026-10-03,Notebook,20,2.50
N-2002,2026-10-15,Desk lamp,3,24.00
CSV
cat > incoming/2026-10/accra.csv <<'CSV'
order_id,date,product,quantity,unit_price
A-3001,2026-10-05,Printer ink,4,18.00
A-3002,2026-10-12,Notebook,6,2.50
A-3003,2026-10-28,Stapler,5,6.40
CSV
cat > incoming/2026-10/kampala.csv <<'CSV'
order_id,date,product,quantity,unit_price
K-4001,2026-10-07,Stapler,2,6.40
K-4002,2026-10-30,Desk lamp,2,24.00
CSVThe files are deliberately tiny, so you can check every number by hand. With real exports the code does not change. In your own setup, the branches drop their files into the month's folder, or you save email attachments there. Agree the file names with them once; the script holds them to it.
Check it worked
ls incoming/2026-10The output lists accra.csv, kampala.csv, lagos.csv and nairobi.csv.
Step 3 · Check every file before you use it
A report built on a missing file looks just as finished as a correct one. So the first job is to collect every problem with the month's files and stop if there are any. Create checks.py:
cat > checks.py <<'PY'
from pathlib import Path
import pandas as pd
BRANCHES = ["lagos", "nairobi", "accra", "kampala"]
COLUMNS = ["order_id", "date", "product", "quantity", "unit_price"]
class InputError(Exception):
"""This month's files cannot be used as they are."""
def load_branch(path: Path, month: str, problems: list[str]) -> pd.DataFrame | None:
df = pd.read_csv(path, dtype=str, encoding="utf-8-sig")
missing = [col for col in COLUMNS if col not in df.columns]
if missing:
problems.append(f"{path.name}: missing columns {', '.join(missing)}")
return None
df = df[COLUMNS].assign(
date=pd.to_datetime(df["date"], format="%Y-%m-%d", errors="coerce"),
quantity=pd.to_numeric(df["quantity"], errors="coerce"),
unit_price=pd.to_numeric(df["unit_price"], errors="coerce"),
)
unreadable = df[["date", "quantity", "unit_price"]].isna().any(axis=1)
if unreadable.any():
problems.append(f"{path.name}: {unreadable.sum()} row(s) with a bad date or number")
outside = ~unreadable & (df["date"].dt.strftime("%Y-%m") != month)
if outside.any():
problems.append(f"{path.name}: {outside.sum()} row(s) dated outside {month}")
return df.assign(branch=path.stem.title())
def load_month(folder: Path, month: str) -> pd.DataFrame:
if not folder.is_dir():
raise InputError(f"{folder} does not exist")
problems: list[str] = []
frames = []
for branch in BRANCHES:
path = folder / f"{branch}.csv"
if not path.exists():
problems.append(f"{path.name}: file is missing")
continue
df = load_branch(path, month, problems)
if df is not None:
frames.append(df)
extra = sorted(p.name for p in folder.glob("*.csv") if p.stem not in BRANCHES)
if extra:
problems.append(f"unexpected files: {', '.join(extra)}")
if frames:
data = pd.concat(frames, ignore_index=True)
repeated = data["order_id"][data["order_id"].duplicated()].unique()
if len(repeated):
problems.append(f"order ids used more than once: {', '.join(repeated)}")
if problems:
raise InputError("\n".join(problems))
return data[["branch", *COLUMNS]]
PYA few choices here matter more than they look:
- Read everything as text first (
dtype=str), then convert witherrors="coerce". A quantity typed astwobecomes a missing value you can count and report, not a crash halfway through, and not a silently text-typed column. - Keep going after a problem. Each check appends to
problemsand the code moves on, so one run tells you about every broken file at once. You fix them all, then run again, instead of finding them one per run. - Check the month. A row dated 1 October in the September folder usually means someone exported the wrong date range. Summing it would double-count it next month.
- Reject extra files. A copy saved as
nairobi (1).csvis a sign that someone sent the file twice and may have changed it. A person should decide which one is right. utf-8-sigreads plain UTF-8 and also the UTF-8 files Excel saves with a hidden marker at the start, which would otherwise end up glued to the first column name. Branch exports often include accented or non-English names, for example from a French-speaking office in Abidjan or Dakar, and this keeps them intact.
Check it worked
Load October and count what came in:
uv run python -c "from pathlib import Path; from checks import load_month; d = load_month(Path('incoming/2026-10'), '2026-10'); print(len(d), 'rows from', d['branch'].nunique(), 'branches')"The output is 10 rows from 4 branches.
Now make a broken month on purpose, the way real months go wrong. September has a renamed column in Lagos, a mistyped quantity and a row from the wrong month in Nairobi, a duplicate Nairobi file, and no Accra or Kampala files at all:
mkdir -p incoming/2026-09
cat > incoming/2026-09/lagos.csv <<'CSV'
order_id,date,product,qty,unit_price
L-0901,2026-09-04,Notebook,8,2.50
CSV
cat > incoming/2026-09/nairobi.csv <<'CSV'
order_id,date,product,quantity,unit_price
N-0901,2026-09-11,Stapler,3,6.40
N-0902,2026-10-01,Notebook,5,2.50
N-0903,2026-09-19,Desk lamp,two,24.00
CSV
cp incoming/2026-09/nairobi.csv "incoming/2026-09/nairobi (1).csv"
uv run python - <<'PY'
from pathlib import Path
from checks import InputError, load_month
try:
load_month(Path("incoming/2026-09"), "2026-09")
except InputError as err:
print(err)
PYAll six problems come out in one go:
lagos.csv: missing columns quantity
nairobi.csv: 1 row(s) with a bad date or number
nairobi.csv: 1 row(s) dated outside 2026-09
accra.csv: file is missing
kampala.csv: file is missing
unexpected files: nairobi (1).csvStep 4 · Build the summary
The summary has one row per branch: number of orders, units sold, revenue and the average order value, sorted by revenue, with a total row at the bottom. Create summary.py:
cat > summary.py <<'PY'
import pandas as pd
def with_revenue(data: pd.DataFrame) -> pd.DataFrame:
return data.assign(revenue=(data["quantity"] * data["unit_price"]).round(2))
def build_summary(data: pd.DataFrame) -> pd.DataFrame:
branches = (
data.groupby("branch", as_index=False)
.agg(
orders=("order_id", "nunique"),
units=("quantity", "sum"),
revenue=("revenue", "sum"),
)
.sort_values("revenue", ascending=False, ignore_index=True)
)
total = pd.DataFrame(
{
"branch": ["All branches"],
"orders": [branches["orders"].sum()],
"units": [branches["units"].sum()],
"revenue": [branches["revenue"].sum()],
}
)
summary = pd.concat([branches, total], ignore_index=True)
return summary.assign(
revenue=summary["revenue"].round(2),
average_order=(summary["revenue"] / summary["orders"]).round(2),
)
PYThe average order value is worked out after the total row is added, from that row's own revenue and orders. The overall average is total revenue divided by total orders, which is not the same as the average of the four branch averages. A copy-and-paste report often gets this wrong because =AVERAGE() over the column above is the obvious formula.
Check it worked
uv run python -c "from pathlib import Path; from checks import load_month; from summary import build_summary, with_revenue; print(build_summary(with_revenue(load_month(Path('incoming/2026-10'), '2026-10'))).to_string(index=False))"The output is:
branch orders units revenue average_order
Nairobi 2 23 122.0 61.00
Accra 3 15 119.0 39.67
Lagos 3 13 85.0 28.33
Kampala 2 4 60.8 30.40
All branches 10 55 386.8 38.68Check one row by hand against the CSV: Lagos sold 10 notebooks at 2.50, 2 printer inks at 18.00 and 1 lamp at 24.00, which is 25 + 36 + 24 = 85.
Step 5 · Write the workbook
pandas writes DataFrames to sheets; XlsxWriter, used as pandas' Excel engine, adds the parts that make a report readable. Create workbook.py:
cat > workbook.py <<'PY'
from pathlib import Path
import pandas as pd
HEADERS = ["Branch", "Orders", "Units", "Revenue", "Average order"]
FIRST_ROW = 3 # rows 0-1 hold the title, row 2 the headers
def write_workbook(summary: pd.DataFrame, data: pd.DataFrame, path: Path, month: str) -> None:
with pd.ExcelWriter(
path, engine="xlsxwriter", date_format="yyyy-mm-dd", datetime_format="yyyy-mm-dd"
) as writer:
book = writer.book
title = book.add_format({"bold": True, "font_size": 14})
header = book.add_format({"bold": True, "bg_color": "#D9DCE1", "bottom": 1})
whole = book.add_format({"num_format": "#,##0"})
money = book.add_format({"num_format": "#,##0.00"})
# Summary sheet: a title, our own header row, then the numbers.
summary.to_excel(writer, sheet_name="Summary", index=False, header=False, startrow=FIRST_ROW)
sheet = writer.sheets["Summary"]
sheet.write(0, 0, f"Branch sales, {month}", title)
sheet.write_row(FIRST_ROW - 1, 0, HEADERS, header)
sheet.set_column(0, 0, 16)
sheet.set_column(1, 2, 10, whole)
sheet.set_column(3, 4, 14, money)
sheet.freeze_panes(FIRST_ROW, 0)
# A native column chart of revenue, branches only (not the total row).
last_branch_row = FIRST_ROW + len(summary) - 2
chart = book.add_chart({"type": "column"})
chart.add_series(
{
"name": "Revenue",
"categories": ["Summary", FIRST_ROW, 0, last_branch_row, 0],
"values": ["Summary", FIRST_ROW, 3, last_branch_row, 3],
}
)
chart.set_title({"name": f"Revenue by branch, {month}"})
chart.set_legend({"none": True})
sheet.insert_chart("G3", chart)
# Data sheet: every order, with a frozen header and filter buttons.
data.to_excel(writer, sheet_name="Data", index=False)
rows = writer.sheets["Data"]
rows.set_column(0, 3, 13)
rows.set_column(4, 4, 10, whole)
rows.set_column(5, 6, 12, money)
rows.freeze_panes(1, 0)
rows.autofilter(0, 0, len(data), len(data.columns) - 1)
PYWhat each part does:
writer.bookandwriter.sheetsare XlsxWriter's own workbook and worksheet objects, so anything XlsxWriter can do is available after pandas has written the cells.- Your own header row.
header=False, startrow=3leaves room above the data for a title and a header row in your format, with readable names instead ofaverage_order. - Number formats on columns. pandas writes numbers without a format, and XlsxWriter then applies the column's format to them. The cells stay real numbers, so readers can still add them up, but show as
1,234.50instead of1234.5. Rounding happened in pandas; the format only changes how a value looks. freeze_panes(3, 0)keeps the title and headers on screen while scrolling, the same as View, Freeze Panes in Excel. On the data sheet,freeze_panes(1, 0)freezes the header row.- A native chart, not a picture. Its ranges are written as
[sheet, first_row, first_col, last_row, last_col]counted from 0, and stop one row before the total, so the total bar does not dwarf the branches. Because the chart points at cells, anyone who corrects a number in the workbook sees the chart update. autofilteradds filter buttons to the data sheet's header row, so a branch manager can look at their own orders.
Rows are counted from the length of the summary, so the chart range follows when you add a fifth branch to BRANCHES. Nothing in this file needs editing month to month.
Check it worked
Write a test workbook from the October data:
uv run python -c "from pathlib import Path; from checks import load_month; from summary import build_summary, with_revenue; from workbook import write_workbook; d = with_revenue(load_month(Path('incoming/2026-10'), '2026-10')); write_workbook(build_summary(d), d, Path('test.xlsx'), '2026-10'); print(Path('test.xlsx').stat().st_size > 0)"
rm test.xlsxThe output is True: the file was written. The next step gives it a proper name and the step after checks what is inside.
Step 6 · Run it from the command line by month
Now join the pieces into a command. Create report.py:
cat > report.py <<'PY'
import argparse
import re
import sys
from datetime import date, timedelta
from pathlib import Path
from checks import InputError, load_month
from summary import build_summary, with_revenue
from workbook import write_workbook
HERE = Path(__file__).resolve().parent
def month_arg(text: str) -> str:
if not re.fullmatch(r"\d{4}-(0[1-9]|1[0-2])", text):
raise argparse.ArgumentTypeError(f"use YYYY-MM, for example 2026-10, not {text!r}")
return text
def previous_month(today: date) -> str:
last_day = today.replace(day=1) - timedelta(days=1)
return last_day.strftime("%Y-%m")
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Build the monthly branch sales workbook.")
parser.add_argument("month", nargs="?", type=month_arg, help="YYYY-MM; defaults to last month")
parser.add_argument("--incoming", type=Path, default=HERE / "incoming")
parser.add_argument("--out", type=Path, default=HERE / "reports")
args = parser.parse_args(argv)
month = args.month or previous_month(date.today())
try:
data = with_revenue(load_month(args.incoming / month, month))
except InputError as err:
print(f"Cannot build the {month} report:\n{err}", file=sys.stderr)
return 1
summary = build_summary(data)
args.out.mkdir(parents=True, exist_ok=True)
path = args.out / f"branch-report-{month}.xlsx"
write_workbook(summary, data, path, month)
print(f"Wrote {path.name}: {len(data)} orders from {data['branch'].nunique()} branches")
return 0
if __name__ == "__main__":
sys.exit(main())
PY
uv run report.py 2026-10The month is a required shape, YYYY-MM, checked before anything is read, because it names both the input folder and the output file. With no month, the script uses last month, which is what you want when it runs on the first days of a new month. The default folders sit next to report.py, so the command works from any directory.
The exit code says how it went: 0 for a report written, 1 when the input files are not usable, and 2 (argparse's own code) when the command itself is wrong. A scheduler or a colleague's script can act on that without reading the text.
Running the same month again overwrites that month's file, which is what you want after a branch sends a corrected export. If the workbook is open in Excel on Windows, close it first: Excel locks open files, and Python gets a permission error.
Check it worked
The output is Wrote branch-report-2026-10.xlsx: 10 orders from 4 branches, and the file is in reports/. Now try the broken September and a badly typed month:
ls reports
uv run report.py 2026-09 || echo "exit code $?"
uv run report.py Oct || echo "exit code $?"September prints Cannot build the 2026-09 report: with the same six problems as before, then exit code 1, and no September file appears in reports/. Oct prints a usage line, then error: argument month: use YYYY-MM, for example 2026-10, not 'Oct' and exit code 2.
Step 7 · Read the workbook back to check it
Opening the file and looking is a good habit, but a script that checks the workbook catches what an eye skims past. Create check_report.py. It uses openpyxl to read the sheets, formats and frozen panes, looks inside the .xlsx file (a zip archive) for the chart, and uses pandas to compare the summary total with the data sheet:
cat > check_report.py <<'PY'
import sys
import zipfile
import pandas as pd
from openpyxl import load_workbook
path = sys.argv[1]
book = load_workbook(path)
summary = book["Summary"]
data = book["Data"]
print("sheets:", book.sheetnames)
print("title:", summary["A1"].value)
print("summary frozen at:", summary.freeze_panes, "| data frozen at:", data.freeze_panes)
print("revenue format:", summary["D4"].number_format)
for row in summary.iter_rows(min_row=4, values_only=True):
print(row[:5])
with zipfile.ZipFile(path) as archive:
charts = [name for name in archive.namelist() if name.startswith("xl/charts/chart")]
print("charts:", charts)
rows = pd.read_excel(path, sheet_name="Data")
total = summary.cell(row=summary.max_row, column=4).value
print("data rows:", len(rows), "| filter:", data.auto_filter.ref)
print("revenue on Data sheet:", round(rows["revenue"].sum(), 2), "| total on Summary:", total)
assert book.sheetnames == ["Summary", "Data"]
assert charts, "no chart in the workbook"
assert round(rows["revenue"].sum(), 2) == total, "Summary total does not match the Data sheet"
print("workbook OK")
PY
uv run check_report.py reports/branch-report-2026-10.xlsxCheck it worked
The output is:
sheets: ['Summary', 'Data']
title: Branch sales, 2026-10
summary frozen at: A4 | data frozen at: A2
revenue format: #,##0.00
('Nairobi', 2, 23, 122, 61)
('Accra', 3, 15, 119, 39.67)
('Lagos', 3, 13, 85, 28.33)
('Kampala', 2, 4, 60.8, 30.4)
('All branches', 10, 55, 386.8, 38.68)
charts: ['xl/charts/chart1.xml']
data rows: 10 | filter: A1:G11
revenue on Data sheet: 386.8 | total on Summary: 386.8
workbook OKA4 means rows 1 to 3 stay put when you scroll. The numbers show as 122 rather than 122.0 because Excel stores numbers without a type; the #,##0.00 format is what shows 122.00 on screen.
Then open reports/branch-report-2026-10.xlsx in Excel, LibreOffice Calc or a spreadsheet app on your phone. You should see the title in large bold type, a grey header row, revenue with two decimals and thousands separators, a column chart with four bars to the right of the table, and a second sheet named Data with filter buttons on its header row. The file is about 9 KB, small enough to send over a mobile connection on a prepaid bundle without thinking twice.
Step 8 · Run it every month
Because the month defaults to last month, the same command works unattended. On a Linux server or a Mac that stays on, a cron entry like this one runs the report at 06:00 on the 2nd of each month, giving branches a day to send their files, and appends what it printed to a log:
0 6 2 * * cd "$HOME/branch-report-demo" && /full/path/to/uv run report.py >> reports/cron.log 2>&1Replace /full/path/to/uv with the output of command -v uv. Cron runs with a minimal PATH that usually does not include where uv is installed, and it uses the machine's time zone, so check that the server's clock agrees with your office's month end. Add the line with crontab -e; schedule jobs with cron covers editing and checking crontabs.
When a month's files are not right, the run exits with code 1 and the log lists every problem. Fix the files and run uv run report.py 2026-11 (with the month in question) by hand.
Check it worked
Confirm what month an unattended run would pick on a given date:
uv run python -c "from datetime import date; from report import previous_month; print(previous_month(date(2026, 1, 15)), previous_month(date(2026, 11, 2)))"The output is 2025-12 2026-10: a run in January reports on December of the year before.
Step 9 · Clean up
Remove the demo project. Python and uv stay installed. If you added the cron entry, delete that line with crontab -e first:
cd ~
rm -rf ~/branch-report-demoCheck it worked
ls ~/branch-report-demo now reports that there is no such file or directory.
Next steps
- Make the input checks declarative and test them: validate data with pandera before analysis.
- Read the branch files as Excel or Parquet instead of CSV: read Excel, CSV and Parquet files with pandas.
- If your team still builds this report with formulas, map each one to pandas: move from spreadsheet formulas to pandas.
- Schedule it properly and see when a run fails: schedule jobs with cron.
Part of these paths
Related tutorials
- Move from spreadsheet formulas to pandasYou will redo a shop's sales workbook in pandas 3.1, step by step, turning fill down, XLOOKUP, IF, filters, SUMIFS, COUNTIFS and a pivot table into a short Python script that writes its results back to Excel.
- Read Excel, CSV and Parquet files into pandas correctlyYou will load a semicolon-separated CSV with the wrong encoding, a multi-sheet Excel workbook whose headers start on row 4 and a Parquet file into pandas 3.1 with the right types, leading zeros and dates intact, reading only the columns you need.
- Validate data with pandera before you analyse itYou will have a pandera 0.36 schema that checks each monthly sales export, writes every problem to a CSV a colleague can fix, and runs in pytest so a broken file stops the report before it starts.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials