Python for Excel users · Lesson 14 of 14

Project: a monthly sales report in Python

Build a monthly sales report in one Python script: clean, filter the month, look up targets, summarise, pivot, chart and save to Excel.

About 25 minutes · code runs in your browser, nothing to install

Every month the same job: open the export, delete the duplicate rows, filter to last month, add a revenue column, VLOOKUP the targets, build a pivot table, sort the reps, make a chart and copy it all into a new workbook. About 30 clicks, every month, with a chance of a mistake each time. Here is the same report as one script, built from the lessons of this course.

The export sales.csv has one row per sale: Date, Rep, Region, Product, Units and Price. It contains a few rows from February and April, and one sale that was exported twice.

Step 1: load, clean and filter the month

Pythoneditable
import pandas as pd

df = pd.read_csv("sales.csv", parse_dates=["Date"])
print("Rows in the export:", len(df))
df = df.drop_duplicates()
df = df[df["Date"].dt.month == 3].copy()
df["Revenue"] = df["Units"] * df["Price"]
print("March sales:", len(df))
print(df[["Date", "Rep", "Revenue"]].head(3))
Output
Rows in the export: 11
March sales: 8
        Date    Rep  Revenue
1 2026-03-02    Ana   240.00
2 2026-03-03    Ben   159.92
3 2026-03-05  Chloe   180.00

parse_dates turns the Date column into real dates while reading. .copy() makes the filtered table independent, so adding a column to it causes no warning.

Step 2: totals per rep and the target lookup

Targets live in a small table, the kind you would keep on a separate sheet and reach with VLOOKUP. groupby gives the SUMIF per rep, map the lookup.

Pythoneditable
import pandas as pd

df = pd.read_csv("sales.csv", parse_dates=["Date"])
df = df.drop_duplicates()
df = df[df["Date"].dt.month == 3].copy()
df["Revenue"] = df["Units"] * df["Price"]

targets = {"Ana": 400, "Ben": 450, "Chloe": 350, "Dev": 300}
reps = df.groupby("Rep")["Revenue"].sum().round(2).to_frame()
reps["Target"] = reps.index.map(targets)
reps["% of target"] = (reps["Revenue"] / reps["Target"] * 100).round(0)
reps = reps.sort_values("Revenue", ascending=False)
print(reps)
Output
       Revenue  Target  % of target
Rep
Ben     519.92     450        116.0
Chloe   379.90     350        109.0
Ana     375.00     400         94.0
Dev     270.00     300         90.0

Dev's duplicate row was removed in step 1, otherwise he would look twice as good.

Step 3: the pivot table

Pythoneditable
import pandas as pd

df = pd.read_csv("sales.csv", parse_dates=["Date"])
df = df.drop_duplicates()
df = df[df["Date"].dt.month == 3].copy()
df["Revenue"] = df["Units"] * df["Price"]

pt = pd.pivot_table(df, index="Region", columns="Product",
                    values="Revenue", aggfunc="sum", fill_value=0,
                    margins=True, margins_name="Total")
print(pt.round(2))
Output
Product  Chair   Desk    Lamp    Total
Region
East     180.0    0.0  199.90   379.90
North    405.0  240.0    0.00   645.00
South      0.0  360.0  159.92   519.92
Total    585.0  600.0  359.82  1544.82

Step 4: the chart

Pythoneditable
import pandas as pd

df = pd.read_csv("sales.csv", parse_dates=["Date"])
df = df.drop_duplicates()
df = df[df["Date"].dt.month == 3].copy()
df["Revenue"] = df["Units"] * df["Price"]
import matplotlib.pyplot as plt

by_region = df.groupby("Region")["Revenue"].sum().sort_values()
plt.figure(figsize=(6, 3.5))
plt.barh(by_region.index, by_region.values, color="#2f6f9f")
plt.title("March revenue by region")
plt.xlabel("Revenue (€)")
plt.tight_layout()
plt.show()
print(f"Total March revenue: €{df['Revenue'].sum():,.2f}")
Output
Total March revenue: €1,544.82
Chart drawn by this code

Step 5: everything into one workbook

On your own computer, the last step writes each table to its own sheet and puts the chart image in the folder. Run the whole script next month on the new export and the report rebuilds itself.

On your computer: the whole report
import pandas as pd

MONTH = 3
df = pd.read_csv("sales.csv", parse_dates=["Date"]).drop_duplicates()
df = df[df["Date"].dt.month == MONTH].copy()
df["Revenue"] = df["Units"] * df["Price"]

targets = pd.read_excel("targets.xlsx").set_index("Rep")["Target"]
reps = df.groupby("Rep")["Revenue"].sum().to_frame()
reps["Target"] = reps.index.map(targets)
reps["% of target"] = (reps["Revenue"] / reps["Target"] * 100).round(0)

pt = pd.pivot_table(df, index="Region", columns="Product", values="Revenue",
                    aggfunc="sum", fill_value=0, margins=True, margins_name="Total")

with pd.ExcelWriter(f"report_{MONTH:02d}.xlsx") as writer:
    df.to_excel(writer, sheet_name="Data", index=False)
    reps.sort_values("Revenue", ascending=False).to_excel(writer, sheet_name="Reps")
    pt.to_excel(writer, sheet_name="Pivot")

# the chart: the step 4 code, with plt.show() replaced by
# plt.savefig(f"chart_{MONTH:02d}.png", dpi=150, bbox_inches="tight")

Change MONTH (or read it from the file name) and the same script makes next month's report.

Tip: Save the script next to the exports, for example as report.py, and run it with python report.py. That is the "30 clicks" replaced by one command.

✎ Exercise

Add one more part to the report: the best-selling product by units in March. Print the units per product, largest first, then a line like Best seller: Lamp (18 units).

Hint: groupby("Product")["Units"].sum(), sort descending; the first label is units.index[0] and its value units.iloc[0].

Your codewrite your answer, then Run
import pandas as pd

df = pd.read_csv("sales.csv", parse_dates=["Date"])
df = df.drop_duplicates()
df = df[df["Date"].dt.month == 3].copy()
# your code here

Expected output:

Product
Lamp     18
Chair    13
Desk      5
Name: Units, dtype: int64
Best seller: Lamp (18 units)
Show a solution
Solutioneditable
import pandas as pd

df = pd.read_csv("sales.csv", parse_dates=["Date"])
df = df.drop_duplicates()
df = df[df["Date"].dt.month == 3].copy()
units = df.groupby("Product")["Units"].sum().sort_values(ascending=False)
print(units)
print(f"Best seller: {units.index[0]} ({units.iloc[0]} units)")
Output
Product
Lamp     18
Chair    13
Desk      5
Name: Units, dtype: int64
Best seller: Lamp (18 units)

Check yourself

1. Why does the script call drop_duplicates() before any totals?

2. Which line keeps only March?

3. How do you get the report for April next month?

Spotted a mistake on this page? Tell us