DEV Community

Zaima Sohail
Zaima Sohail

Posted on Originally published at Medium on

How I Automate Excel Reports with Python in One Script

Turn a messy spreadsheet into a clean, formatted report with one Python script.

Every week, someone in your office opens the same messy spreadsheet. They delete duplicate rows, hunt for blank cells, fix “north “ so it matches “North”, and rebuild the same pivot tables they built last week. It takes an hour, it’s boring, and one small slip breaks the totals.

I work as a Python developer on business systems, and I see this pattern constantly. The good news is that this kind of work is perfect for automation. In this tutorial, we’ll write one Python script that reads a raw Excel file, cleans it, summarises it, and saves a formatted report with a chart, all in a few seconds.

You only need basic Python. The full code is on GitHub.

What we’ll build

We start with a raw sales file of 215 rows. It has duplicate orders, blank cells, and inconsistent region names. The script turns it into one Excel report with five sheets:

Setup

We need two libraries: pandas for working with the data and openpyxl for reading, writing and formatting Excel files.

pip install pandas openpyxl

You probably don’t have a messy sales file lying around, so the script creates one for you. On the first run, a small function generates 200 orders and deliberately breaks them: it blanks out some cells, turns a few region names into lowercase with trailing spaces, and copies 15 rows to create duplicates. That way anyone can follow along and get the same results.

Here are the imports and file names we’ll use throughout:

from pathlib import Path

import numpy as np

import pandas as pd

from openpyxl import load_workbook

from openpyxl.chart import BarChart, Reference

from openpyxl.styles import Font, PatternFill, Alignment

RAW_FILE = Path(“raw_sales.xlsx”)

REPORT_FILE = Path(“sales_report.xlsx”)

If you want to use your own data instead, just replace raw_sales.xlsx with your file and adjust the column names later on.

Step 1: Read the Excel file

Reading an Excel file with pandas takes one line. pd.read_excel() opens the first sheet and returns a DataFrame, which is basically a spreadsheet you can control with code.

def load_data(path: Path) -> pd.DataFrame:

df = pd.read_excel(path)

print(f”Loaded {len(df)} rows, {df.shape[1]} columns”)

return df

The print line is a small habit worth keeping. When the script runs every week on new files, a quick row count tells you straight away if something looks wrong, like a file that’s half empty. For our sample file it prints Loaded 215 rows, 6 columns.

If your data lives on a different sheet, pass its name: pd.read_excel(path, sheet_name=”January”).

(The function that generates the sample data is in the GitHub repo if you want to see how the mess was made.)

Step 2: Clean the data

This is the part people usually do by hand, and the part where automation saves the most time. Our raw file has three problems: duplicate rows, inconsistent text, and missing values. We’ll fix them one at a time, and keep a few numbers along the way for the report.

Remove duplicates

stats = {“rows_before”: len(df)}

stats[“duplicates_removed”] = int(df.duplicated().sum())

df = df.drop_duplicates().copy()

df.duplicated() marks every row that is an exact copy of an earlier one. Counting them before dropping lets us report how many we removed, which here is 15. That number matters: if your boss asks why the total changed, you have the answer.

Fix inconsistent text

In the raw file, the same region appears as “North”, “north “ and so on. To you, these are the same. To pandas, they’re different values, so a summary would show “North” and “north “ as two separate regions with split totals.

df[“Region”] = df[“Region”].str.strip().str.title()

.str.strip() removes spaces at the start and end, and .str.title() capitalises the first letter. In our sample, this one line fixes 16 inconsistent entries.

We also convert the Date column into real dates, so we can group by month later:

df[“Date”] = pd.to_datetime(df[“Date”], errors=”coerce”)

errors=”coerce” turns anything that isn’t a valid date into a blank instead of crashing the script.

Handle missing values

After removing duplicates, the data still has 12 missing quantities, 8 missing regions and 5 missing prices. The easy option is to fill every blank with 0. Don’t. If a laptop order has no price and you fill it with 0, that order now looks free, and your revenue total is quietly wrong.

Instead, each column gets a fill that makes sense for it:

df[“Region”] = df[“Region”].fillna(“Unknown”)

df[“Quantity”] = df[“Quantity”].fillna(df[“Quantity”].median())

df[“Unit Price”] = df.groupby(“Product”)[“Unit Price”].transform(

lambda s: s.fillna(s.median())

)

• Region: we can’t guess where an order came from, so we label it “Unknown”. The orders stay in the totals, and the report shows openly how many are unassigned.

• Quantity: we use the median. It’s a typical order size, and unlike the average, one huge order can’t pull it up.

• Unit Price: a missing laptop price should be filled with a laptop price, not the average of laptops and mice. groupby(“Product”) with transform fills each blank with the median price of that same product.

That last line is the one I’d point to if someone asked what separates a careful cleaning script from a quick one.

Add calculated columns

Finally, we add Revenue and Month, which the summaries need:

df[“Revenue”] = df[“Quantity”] * df[“Unit Price”]

df[“Month”] = df[“Date”].dt.to_period(“M”).astype(str)

stats[“rows_after”] = len(df)

We’re now down from 215 messy rows to 200 clean ones, with no blank cells left.

Step 3: Build summary tables

Now the data is clean, summaries are easy. These replace the pivot tables someone would otherwise rebuild by hand every week.

def build_summaries(df: pd.DataFrame) -> dict[str, pd.DataFrame]:

by_region = (df.groupby(“Region”, as_index=False)

.agg(Orders=(“Order ID”, “count”),

Units=(“Quantity”, “sum”),

Revenue=(“Revenue”, “sum”))

.sort_values(“Revenue”, ascending=False))

by_product = (df.groupby(“Product”, as_index=False)

.agg(Units=(“Quantity”, “sum”), Revenue=(“Revenue”, “sum”))

.sort_values(“Revenue”, ascending=False))

monthly = df.pivot_table(index=”Month”, columns=”Region”,

values=”Revenue”, aggfunc=”sum”, fill_value=0)

monthly = monthly.reset_index()

return {“By Region”: by_region, “By Product”: by_product, “Monthly”: monthly}

groupby() with .agg() works like a pivot table with named results. Each line inside .agg() reads as “new column = (source column, calculation)”, so Orders=(“Order ID”, “count”) counts orders per region. Sorting by revenue puts the best performers at the top.

pivot_table() builds a grid: months down the side, regions across the top, revenue in each cell. fill_value=0 matters here, because a region with no sales in a month should show 0, not a blank.

Here’s the region summary for our sample data:

Notice the “Unknown” row. Eight orders and 3,495 in revenue would have quietly disappeared if we had simply deleted rows with missing regions.

Step 4: Save multiple sheets

A report is much easier to use when everything lives in one file instead of five. pd.ExcelWriter lets us write several DataFrames into separate sheets of the same workbook.

def save_report(df, summaries, stats, path):

with pd.ExcelWriter(path, engine=”openpyxl”) as writer:

overview = pd.DataFrame({

“Metric”: [“Rows before cleaning”, “Duplicates removed”,

“Rows after cleaning”, “Total revenue”],

“Value”: [stats[“rows_before”], stats[“duplicates_removed”],

stats[“rows_after”], round(df[“Revenue”].sum(), 2)],

})

overview.to_excel(writer, sheet_name=”Overview”, index=False)

for name, table in summaries.items():

table.to_excel(writer, sheet_name=name, index=False)

df.to_excel(writer, sheet_name=”Clean Data”, index=False)

The with block opens the file, writes each sheet, and saves and closes it automatically at the end.

I put the Overview sheet first on purpose. It’s the first thing anyone sees when they open the file: 215 rows came in, 15 duplicates were removed, 200 rows remain, and total revenue is 116,175. Those four numbers also make the report easy to trust, because anyone can see exactly what the cleaning changed.

index=False stops pandas from adding an extra column of row numbers, which nobody wants in a business report.

Step 5: Add formatting and a chart

A plain pandas export works, but it looks unfinished: narrow columns, plain headers, no visuals. A few lines of openpyxl turn it into something you’d happily send to a manager.

def format_report(path):

wb = load_workbook(path)

header_fill = PatternFill(“solid”, fgColor=”1F4E78")

header_font = Font(bold=True, color=”FFFFFF”)

for ws in wb.worksheets:

for cell in ws[1]:

cell.fill = header_fill

cell.font = header_font

cell.alignment = Alignment(horizontal=”center”)

for col in ws.columns:

width = max(len(str(c.value)) if c.value is not None else 0 for c in col)

ws.column_dimensions[col[0].column_letter].width = min(width + 3, 30)

ws.freeze_panes = “A2”

For every sheet, this does three things:

  1. Styles the header row with a dark blue background and bold white text. ws[1] means “row 1”.

  2. Auto-sizes each column to fit its longest value, capped at 30 characters so one long entry can’t make a column huge.

  3. Freezes the header row with freeze_panes = “A2”, so the headers stay visible when you scroll down 200 rows.

Then we add a bar chart to the By Region sheet:

ws = wb[“By Region”]

chart = BarChart()

chart.title = “Revenue by Region”

chart.y_axis.title = “Revenue”

data = Reference(ws, min_col=4, min_row=1, max_row=ws.max_row)

cats = Reference(ws, min_col=1, min_row=2, max_row=ws.max_row)

chart.add_data(data, titles_from_data=True)

chart.set_categories(cats)

ws.add_chart(chart, “F2”)

wb.save(path)

Reference points the chart at cells in the sheet. Column 4 holds Revenue (including its header, so the chart picks up the series name), and column 1 holds the region names for the x-axis. add_chart(chart, “F2”) places the chart next to the table.

Because this is a real Excel chart, not an image, anyone can click it, restyle it, or change its type in Excel.

Putting it all together

The main() function runs every step in order:

def main():

if not RAW_FILE.exists():

create_sample_data(RAW_FILE)

df = load_data(RAW_FILE)

clean, stats = clean_data(df)

summaries = build_summaries(clean)

save_report(clean, summaries, stats, REPORT_FILE)

format_report(REPORT_FILE)

print(f”Duplicates removed: {stats[‘duplicates_removed’]}”)

print(f”Report saved: {REPORT_FILE}”)

if __name__ == “__main__”:

main()

Run it with python excel_report_automation.py. The whole thing finishes in a few seconds, and the output looks like this:

Sample data created: raw_sales.xlsx (215 rows)

Loaded 215 rows, 6 columns

Duplicates removed: 15

Report saved: sales_report.xlsx

Going further

The script already saves time, but a few small additions make it fully hands-off:

• Run it on a schedule. On Windows, use Task Scheduler to run the script every Monday at 9 a.m. On Mac or Linux, a cron job does the same thing. The report is ready before anyone opens their laptop.

• Email the report automatically. Python’s built-in smtplib and email modules can attach sales_report.xlsx and send it to your team as soon as it’s created.

• Process a whole folder. If you receive one file per branch or per month, loop over them with Path(“data”).glob(“*.xlsx”), combine them with pd.concat(), and build one combined report.

• Make it reusable. Move the column names and file paths into a small config file, so the same script works for different reports without editing the code.

Conclusion

We took a messy 215-row spreadsheet and, with one Python script, turned it into a clean, five-sheet report with a chart. Along the way, we removed 15 duplicates, fixed 16 inconsistent region names, and filled 25 missing values in ways that keep the totals honest.

The biggest lesson isn’t any single pandas function. It’s that cleaning decisions, like how to fill a missing price, are business decisions. Writing them down in code makes them consistent every single week.

The complete code is on GitHub. Try it on your own data, and if you get stuck or have ideas for improvements, leave a comment. I’d love to hear what you automate with it.

If you found this useful, follow me for more practical Python, data science and machine learning tutorials.

Top comments (0)