Compare Two Excel Files with Python: Find Every Changed Cell in One Run

Every month there are spreadsheets to compare: the supplier's new price list against the old one, the customer list a colleague sends back against the version exported from the system, the quotation you edited three times against the copy the client signed. Open both files side by side and read line by line, and a thousand rows blur long before you finish. Most reviews end with a vague feeling that something looks different.

The awkward part is that the real changes usually amount to a dozen cells. Hunting a dozen cells across twenty thousand by eye is the least efficient work in the office: finding them is luck, missing them is normal.

This article builds a comparison tool in a few dozen lines of Python. It produces three lists, changed, added and removed, and writes them into a colour-coded workbook you can forward without explanation.

First, separate the three kinds of difference

  • Changed: same item, same row, but a few cells now hold different values. Most common, easiest to miss.
  • Added: rows that exist only in the new file. Could be new products, could be duplicate entries.
  • Removed: rows that were in the old file and are gone.

Keep them apart, because the reasons and the follow-up differ. Changes are usually a price rise or a quantity edit. Additions need the question "is this a new product?". Removals need a different one: discontinued, or did the other side drop a line by accident?

The key idea: align on an ID, never on a row number

The most common mistake is comparing row 15 with row 15. Insert one row in the new file and everything below shifts, so every line registers as a change and the report becomes useless.

Pick a unique column as the key instead: item code, order number, customer code, anything that never repeats. Index both files on it and compare. Insertions and deletions then no longer disturb the rows around them.

Install and load

pip install pandas openpyxl
import pandas as pd OLD = "D:/reports/pricelist_oct.xlsx" NEW = "D:/reports/pricelist_nov.xlsx" KEY = "ItemCode" # dtype=str: read everything as text so 1234 and "1234" are not treated as two values old = pd.read_excel(OLD, dtype=str).fillna("").set_index(KEY).sort_index() new = pd.read_excel(NEW, dtype=str).fillna("").set_index(KEY).sort_index() print("old rows", len(old), "new rows", len(new))

The dtype=str line cannot be skipped. The same cell may be a number in file A and text in file B, because of a leading space or an export that set the column to text format. pandas treats those as different values, and you get a wall of false alarms reading "1,200 changed to 1,200". Read everything as text and compare strings: the behaviour is predictable.

fillna("") turns empty cells into empty strings, so you never compare NaN with NaN and get a mismatch that has no meaning.

Step one: split added, removed and common

added = new.index.difference(old.index) removed = old.index.difference(new.index) common = old.index.intersection(new.index) print("added", len(added), "removed", len(removed), "common", len(common))

Three sets and you already know how different the two files are in size. If the added and removed counts are both large, the two files are probably not the same table at all, and comparing them is the wrong approach.

Step two: compare cell by cell and extract the edits

cols = [c for c in old.columns if c in new.columns] rows = [] for k in common: for c in cols: a = str(old.at[k, c]).strip() b = str(new.at[k, c]).strip() if a != b: rows.append({KEY: k, "Field": c, "Old": a, "New": b}) diff = pd.DataFrame(rows) print("changed cells:", len(diff))

A thousand rows across twenty columns is twenty thousand cells, and this double loop finishes in a second or two on an ordinary office PC. The output has one row per changed cell, nothing else, and it can go straight into an email: "Item AQ-1042 unit price moved from 12.5 to 14.0, is that a typo?" That is a far better question than "the price list looks like it went up".

Step three: write the colour-coded report

from openpyxl import Workbook from openpyxl.styles import PatternFill FILL = {"Changed": PatternFill("solid", fgColor="FFF2CC"), "Added": PatternFill("solid", fgColor="D9EAD3"), "Removed": PatternFill("solid", fgColor="F4CCCC")} def dump(df, ws, title): ws.title = title ws.append(list(df.columns)) for r in df.itertuples(index=False): ws.append([str(v) for v in r]) for row in ws.iter_rows(min_row=2): for cell in row: cell.fill = FILL[title] wb = Workbook() dump(diff, wb.active, "Changed") dump(new.loc[added].reset_index(), wb.create_sheet(), "Added") dump(old.loc[removed].reset_index(), wb.create_sheet(), "Removed") wb.save("D:/reports/diff_report_20261105.xlsx")

Three worksheets: yellow for changed, green for added, red for removed. Put the date in the file name, and next time someone asks whether a price changed last month, you have the record. Nobody reading the report needs to know Python; they open it in Excel.

A real case: a 12-person trading firm

Every month they reconcile the supplier price list: 1,240 rows and 18 columns, roughly 22,000 cells. The manual method was two files side by side, read line by line, 45 to 60 minutes on average, with a second person cross-checking because one reader always misses something.

With the script, loading and comparing takes six to ten seconds. On the first run it caught three price increases. One item moved from 12.5 to 14.0, a 12 percent rise, while the supplier's email mentioned only a "general 3 percent increase". Entering the email's figure would have understated the month's cost by about HK$9,000. A human can find that, but usually only on the third pass.

From the second month the team does two things: run the script, then look at how many rows are yellow. The price list check went from half a day to five minutes.

Four common traps

  • Thousand separators and full-width digits: 1,200 and 1200 are the same number and different strings. Strip them with .str.replace(",", "").str.strip() before comparing.
  • Different date formats: 2026-11-05 and 5/11/2026 are the same day. Normalise with pd.to_datetime first.
  • Decimal places: 1.10 and 1.1 are the same value. Convert amount columns to float and round to two places.
  • Hidden rows and merged cells: both change the row count you read versus the row count you see. Unhide and unmerge before running.

All four come down to one point: a diff tool faithfully reports "the strings differ". It does not know that you consider two values equivalent. So clean the data before comparing, not after.

When not to use it

If the two files have completely different structures, one landscape and one portrait for instance, or if more than thirty percent of the content changed, a diff is the wrong tool and rebuilding the report is faster. The real value is the case where most of the file is identical and a small part moved, which covers about nine out of ten version comparisons in an office.

Summary

Python Tutorial: comparing two Excel files does not have to be done by eye. Index both files on a unique ID, read everything as text with dtype=str, compare cell by cell to extract the edits, then write a yellow-green-red workbook. A thousand rows finish in six seconds and not one changed cell slips through. The whole tool is a few dozen lines, and it works on any before-and-after pair your company has: price lists, quotations, customer lists, monthly figures.