Automate Excel with Python

How to Automate Excel with Python: A Practical Guide

SS
Shajul Islam Sumon
November 03, 2026
  • 10 mins read
Laptop displaying a sales spreadsheet beside handwritten notes for a recurring reporting task.
In this article

Monthly spreadsheet work becomes easier to repeat when its rules are clear. Follow a practical Python example that combines sales files, separates records needing review and creates a checked summary.

You can automate Excel with Python by writing a script that reads spreadsheets, checks their records, performs calculations and creates a report. In this guide, you will use pandas and openpyxl to combine three sales workbooks, flag incomplete records and summarise accepted sales by region.

Imagine receiving the same spreadsheets every month. You check their columns, copy the records, correct inconsistent labels and rebuild the summary. Could a script handle that routine?

Yes—once you can explain the rules it should follow.

This tutorial is for readers with basic Python knowledge who want to complete their first repeatable Excel reporting task.

When should you use Python for Excel automation?

Comparison of Excel, Power Query and Python as starting points for different spreadsheet tasks.

Python is worth considering when you repeat a process with identifiable inputs, consistent rules and a result you can check.

“Prepare the monthly report” is too broad. “Combine three workbooks, flag incomplete orders and total accepted sales by region” gives you a practical starting point.

Your task

A useful starting point

Make a small correction or perform a one-off calculation.

Work directly in Excel.

Repeatedly import, combine and transform tables within Excel.

Assess Power Query first.

Apply custom validation and coordinate file processing with reporting.

Consider a standalone Python script.

Update a complex workbook containing macros or specialised features.

Check feature support before choosing a library.

Excel already supports repeatable data preparation. Microsoft’s Power Query overview explains its tools for connecting, transforming, combining and refreshing data.

This guide uses standalone Python on your computer. It does not use Python in Excel, which runs Python code in Microsoft’s cloud and does not provide direct access to your local files.

Read about the Python in Excel environment.

What you will build

You will process three fictional sales workbooks:

  • sales_january.xlsx

  • sales_february.xlsx

  • sales_march.xlsx

Each contains a worksheet called Sales. The script reads their records and creates a new workbook called sales_report.xlsx.

Output sheet

Purpose

Summary

Shows regional sales values, the included total and record counts.

Accepted_Data

Contains records that pass validation, with calculated sales values.

Needs_Review

Retains rejected field values, their source locations and reasons for review.

The sample contains 12 non-empty records. Nine pass validation, three need review, and the accepted records total £485.00.

These are deliberately constructed training figures. Each row represents one complete order for one product. Sales value means quantity multiplied by unit price; it excludes tax, discounts, returns and costs.

The result is therefore included sales value, rather than profit or the complete value of every incoming order.

Three sales workbooks are checked, with nine accepted records summarised and three records retained for review.

What you need before starting

You should be able to run a Python script and recognise variables, loops, functions and conditions. You do not need advanced programming knowledge.

If these foundations are unfamiliar, start with . Python for Data Analysis: Complete Beginner-to-Practical Guide before adapting the example.

The project uses two libraries:

Library

Its role in this example

pandas

Combines records into tables and exports the report tables.

openpyxl

Reads workbook cells, checks the original headers and formats the output.

A pandas DataFrame is a table with labelled rows and columns. It gives the script a convenient structure for processing spreadsheet records.

The libraries have overlapping capabilities. This example uses openpyxl to inspect the original headers before building DataFrames, helping it catch duplicated or unexpected column names.

 Reference documentation: pandas Excel import options and the openpyxl workbook tutorial.

Set up the example files

excel-automation-draft-and-examples.zip.

Extract the package before running it. Keep automate_excel.py beside the input folder. The script creates its own output folder.

Install the required libraries in your Python environment:

python -m pip install pandas openpyxl

If your computer uses python3 or py, use that command consistently for installation and execution.

The example was tested with Python 3.12.14, pandas 2.2.3 and openpyxl 3.1.5.

Understand the input rules

Every input workbook must contain a Sales worksheet with these five headers in the first row, in this order:

Column

Required value

order_id

Non-empty text, unique across all input records.

order_date

A valid date stored as YYYY-MM-DD text.

region

North, South or West.

quantity

A positive whole number, up to 1,000,000.

unit_price

A positive GBP amount, up to £1,000,000, without fractional pence.

The quantity and price limits are rules for this exercise, not industry standards.

Enter prices without currency symbols or thousands separators. Dates must be text in the specified format: a native Excel date cell needs a different handling rule.

Before continuing: Open a sample workbook and identify its worksheet, five headers and four data rows. Understanding the input is part of building the automation.

Step 1: Find the files and check their structure

The script looks inside input for filenames matching sales_*.xlsx.

Its paths are based on the script’s location. This makes file discovery independent of whichever folder happens to be open in your terminal.

Before combining records, it checks each workbook for:

  • A worksheet named Sales.

  • The five required headers.

  • The correct header order.

  • No duplicated or unexpected extra headers.

A structural problem stops the run with a message identifying the workbook.

That is useful behaviour. A column called 'amount' might represent a unit price or an order total. The script should not guess which meaning applies.

Completely empty data rows are skipped. Every other record receives a source_file and source_row, allowing you to trace it back to the original worksheet.

Checkpoint: If the structure check fails, correct the named workbook before investigating calculations.

Step 2: Separate valid records from records needing review

The sample includes three deliberate problems:

Record

Problem

Script response

JAN-004

Missing quantity.

Sends the record to Needs_Review.

FEB-004

Invalid date: 2026-02-30.

Sends the record to Needs_Review.

MAR-004

Missing region.

Sends the record to Needs_Review.

Each rejected record receives a review reason. The script keeps its original field values and source location.

It also checks for unknown regions, invalid prices and quantities outside the agreed limits.

Decide what can be corrected automatically

The script normalises surrounding spaces and capitalisation in region names. For example, 'north' and 'north' both become 'north'.

That correction is supported by an explicit mapping. An unknown region such as East needs review.

Missing quantities are not replaced with zero, and missing regions are not inferred from other records.

Treat duplicate IDs as a separate problem

Duplicate non-empty order IDs stop the run before a report is created.

Silently deleting a repeated ID could hide a duplicated export or another source problem. Investigate the cause first.

This rule assumes one row per order. If your real workbook contains several product lines for each order, define an appropriate line-level identifier before adapting the script.

For more practice with DataFrames, cleaning and grouping, use Pandas for Data Analysis: A Practical Beginner’s Guide alongside this project.

Checkpoint: Can you explain why each rejected record failed and locate it in its source workbook?

Step 3: Calculate sales and check the totals

For accepted records, the calculation is:

Sales value = quantity × unit price

The script converts prices to integer pence before multiplication and addition. For example, £12.50 becomes 1,250 pence. It converts the results back to pounds when preparing the report.

This keeps the calculation separate from its appearance. Applying a two-decimal currency format in Excel does not itself define a rounding policy.

The expected regional results are:

Region

Included sales value

North

£160.00

South

£145.00

West

£180.00

Total

£485.00

The script also checks that:

  1. Every input record appears in either the accepted or review group.

  2. Accepted-record sales values add up to the regional summary total.

For the original sample:

12 input records = 9 accepted records + 3 review records

These checks establish consistency within the processed data. They cannot prove that the original quantities or prices were entered correctly.

Checkpoint: Your report should show nine accepted records, three review records and £485.00 in included sales.

Step 4: Create a report readers can inspect

The output workbook includes bold headings, filters and frozen header rows. Accepted dates use a consistent format, while prices and sales values display as GBP amounts.

The detail sheets retain source filenames and row numbers. The summary states that review records are excluded.

These details help someone assess the report without reading the Python code.

The script creates a new workbook; it does not reproduce the input workbooks’ layouts, comments, charts or other features. Reading and exporting table data should not be treated as complete workbook preservation.

Before creating the final file, the script writes a temporary workbook and checks its sheet names and detail-row counts. It refuses to replace an existing report.

Run one copy of the script at a time. Its file handling protects against routine accidental replacement, but it is not a complete recovery system for interrupted storage or power loss.

Run the script and inspect the result

Open a terminal in the extracted example folder:

python automate_excel.py

Run Python normally, without the -O option, so the script’s assertion checks remain enabled.

You should receive:

Input: 12 | Accepted: 9 | Needs review: 3

Included sales value: GBP 485.00

Created: <your project folder>/output/sales_report.xlsx

Open the generated workbook and check:

  • The regional figures match the expected table.

  • Accepted_Data contains nine records.

  • Needs_Review contains the three deliberate problems.

  • Source filenames and row numbers identify the original records.

  • The summary explains that review records are excluded.

The package includes a reference report in expected, separate from the script’s output folder.

Excel summary showing £485.00 in accepted sales, nine accepted records and three records needing review.

Fix common problems and rerun safely

Problem

What to check

No matching files found.

Check extraction, folder location, filenames and .xlsx extensions.

Missing Sales worksheet.

Check the worksheet tab name in the named workbook.

Incorrect headers.

Check spelling, order, duplicates and extra columns.

Duplicate order ID.

Investigate the repeated records in the source files.

Unexpected review records.

Read review_reason and compare the values with the input rules.

Output already exists.

Archive or remove the previous generated report before rerunning.

Permission error.

Check folder permissions and whether another program is holding the destination file.

Keep only the intended source files in input. Any additional workbook matching sales_*.xlsx will also be processed.

To practise, make copies of the sample inputs and correct the three invalid records using values you deliberately choose. Archive the previous report, then rerun.

Your new total will depend on those corrections. The original £485.00 is only the expected result for the unchanged sample.

Build on the skills you have practised

Choose one small extension:

  • Add a valid order and predict the new total.

  • Add another permitted region.

  • Introduce a rule for the earliest acceptable order date.

Make one change at a time. Predict its effect, run the script and compare the output with your expectation.

This helps you identify what to practise next. Difficulty expressing a rule suggests working on conditions and functions. Difficulty following records through the process suggests more practice with files and DataFrames.

For broader context on combining analysis tools,  SQL, Python, Power BI: Skills Germany Wants provides related reading.

The Python Programming Bootcamp (Data Analysis & Automation) covers programming foundations, structured data and files, pandas analysis, and automation.

Its syllabus can help you assess those learning gaps. This exact Excel project is not confirmed as a course assignment.

View the course syllabus and prerequisites.

Tags:

Frequently Asked Questions

01 Can Python automate Excel without Excel being installed? +

Yes. This example reads and writes .xlsx files using Python libraries without controlling the Excel application.

You need Excel or another compatible viewer to inspect the workbook visually. Automating features of the Excel application itself is a different task.

02 Should I use pandas or openpyxl? +

Use pandas for processing tables and creating summaries. Use openpyxl for supported workbook and cell-level operations.

This example combines them. Your choice should follow the task and the workbook features involved.

03 Will this preserve my existing workbook formatting? +

The script leaves the input files unchanged and applies its own formatting to a new report.

It does not copy the original workbook layout. For workflows that edit existing files, check the library’s feature support first. The openpyxl documentation warns that unsupported shapes can be lost when loading and saving a workbook.

Check the openpyxl loading and saving guidance.

04 Can openpyxl calculate Excel formulas? +

No. It can store formulas but does not evaluate them.

Loading with data_only=True retrieves a stored result where one exists; it does not recalculate the formula. This tutorial expects literal input values and calculates sales in Python.

Read the openpyxl formula documentation.

05 Does this script support .xls files or macros? +

No. It accepts .xlsx inputs only.

Legacy .xls files and macro-enabled .xlsm workflows require separate handling. Renaming a file extension does not convert the workbook.

06 Why keep rejected records? +

They show what the summary excludes and give you a way to investigate the problem.

Keeping their field values, source locations and review reasons makes corrections easier to trace.

07 Can I schedule the script? +

Yes, after verifying manual runs and defining how unattended execution should work.

Decide how inputs arrive, how reports are named or archived, where logs are stored and how failures will be noticed. This example refuses an existing output, so it needs an explicit output policy before scheduling.

08 Could Power Query handle the same task? +

It may be suitable, particularly if you want to keep recurring imports and transformations inside Excel.

Compare the validation requirements, surrounding workflow and maintenance needs. Choose an approach you can understand, check and run again.

Here your growth begins.

Unleash your potential. Learn anytime, anywhere.