Compare Two Excel Sheets in Python, Even With Different Row Counts
Load both sheets into pandas. If they have the same rows and columns, df_new.compare(df_old) lists every changed cell. If rows were added or removed, merge the two DataFrames with indicator=True, or match rows on a key column, to see what is new, gone or changed. xlwings or openpyxl then colors the differences in the workbook.
Table of contents
Install the packages
You need pandas to compare the data, openpyxl so pandas can read .xlsx files, and xlwings if you want to color the differences through Excel. One pip command installs all three.
pip install openpyxl pandas xlwings
Every script below starts with these imports. The example files are in the GitHub repository for this tutorial, with one folder for sheets of the same shape and one for sheets with different row counts.
from pathlib import Path
import pandas as pd
import xlwings as xw
Same shape: compare()
When both sheets have the same rows and columns in the same order, and only some values changed, the pandas compare method is the shortest route. It returns one row per changed row, with the new value under self and the old value under other.

Define both file paths with pathlib, load each sheet into a DataFrame and compare them:
initial_version = Path.cwd() / "Same_Shape" / "Arrival_Dates.xlsx"
updated_version = Path.cwd() / "Same_Shape" / "Arrival_Dates_Final.xlsx"
df_initial = pd.read_excel(initial_version)
df_update = pd.read_excel(updated_version)
df_initial.shape == df_update.shape # True
# self = updated version, other = initial version
diff = df_update.compare(df_initial, align_axis=1)
diff
With the example files, the result shows a first name that changed from Troy to Troi and four new arrival dates. The number on the left is the pandas row index, which starts at 0 below the header:
First Name Arrival Date
self other self other
10 Troi Troy NaT NaT
21 NaN NaN 2022-12-10 2022-03-23
56 NaN NaN 2022-08-18 2022-02-01
85 NaN NaN 2022-07-26 2022-10-24
99 NaN NaN 2022-12-03 2022-07-09
Columns without a change are left out, and NaN or NaT marks a cell in that row that did not change. Three options change the layout:
align_axis=0stacks the old and new value under each other instead of side by side.keep_shape=Truekeeps every row and column, so the result has the shape of the original sheet.keep_equal=Truefills in the unchanged values instead of NaN.
To keep the result, write it to a new workbook with diff.to_excel(Path.cwd() / "Same_Shape" / "Difference.xlsx").
Highlight changed cells
To see the changes inside the workbook itself, compare the two sheets cell by cell and color every cell that differs. The xlwings version below opens both files in a hidden Excel instance, colors each changed cell light red, adds a comment with the old value, and saves the result as a new file.
with xw.App(visible=False) as app:
initial_wb = app.books.open(initial_version)
initial_ws = initial_wb.sheets(1)
updated_wb = app.books.open(updated_version)
updated_ws = updated_wb.sheets(1)
for cell in updated_ws.used_range:
old_value = initial_ws.range((cell.row, cell.column)).value
if cell.value != old_value:
cell.api.AddComment(f"Value from {initial_wb.name}: {old_value}") # WARNING: Platform specific (!)
cell.color = (255, 71, 76) # light red
updated_wb.save(Path.cwd() / "Same_Shape" / "Difference_Highlighted.xlsx")
xlwings needs Excel installed. The AddComment line goes through the Windows Excel object model, so on a Mac drop it and keep only the color.
Without Excel, for example on a server, openpyxl does the same job directly on the file:
from openpyxl import load_workbook
from openpyxl.comments import Comment
from openpyxl.styles import PatternFill
red = PatternFill(fill_type="solid", start_color="FF474C", end_color="FF474C")
ws_old = load_workbook(initial_version).active
wb_new = load_workbook(updated_version)
ws_new = wb_new.active
for row in ws_new.iter_rows():
for cell in row:
old_value = ws_old[cell.coordinate].value
if cell.value != old_value:
cell.fill = red
cell.comment = Comment(f"Old value: {old_value}", "Python")
wb_new.save(Path.cwd() / "Same_Shape" / "Difference_Highlighted.xlsx")
I tested the pandas and openpyxl code in this post with pandas 2.2 and openpyxl 3.1 on two small sample sheets: it colored exactly the changed name and the changed date, each with the old value in a comment. Both versions compare cell A2 with cell A2, so they only make sense when the rows line up. For sheets with different row counts, use the merge below.
Different row counts: merge
When rows were added or removed, compare stops with a ValueError, because the two DataFrames no longer have the same row labels. An outer merge with an indicator column works for any shape: it keeps every row from both sheets and marks where each one came from.
initial_version = Path.cwd() / "Different_Shape" / "Arrival_Dates.xlsx"
updated_version = Path.cwd() / "Different_Shape" / "Arrival_Dates_Final.xlsx"
df_initial = pd.read_excel(initial_version)
df_update = pd.read_excel(updated_version)
# We need the index information to highlight the rows in Excel
df_update = df_update.reset_index()
# Merge dataframes and add indicator column
df_diff = pd.merge(df_initial, df_update, how="outer", indicator="Exist")
# Show only the difference
df_diff = df_diff.query("Exist != 'both'")
df_diff
The merge matches rows on all shared columns, so a row only counts as both when every value is identical. The Exist column then reads:
- left_only: the row is only in the initial sheet. It was removed, or it is the old version of a changed row.
- right_only: the row is only in the updated sheet. It is new, or it is the new version of a changed row.
The reset_index() line copies each row’s position in the updated sheet into a column named index, which the highlighting step needs later. A merge works like a lookup on every column at once; VLOOKUP in pandas explains merges in more detail.
Added, removed or changed
The merge cannot tell an edited row from a deleted one plus a new one. If your sheets have a column that identifies each row, such as an ID or a customer number, use it as the index: rows whose key is only in one sheet were added or removed, and compare works again on the keys both sheets share.
key = "Last Name" # a column whose values are unique in both sheets
old = pd.read_excel(initial_version).set_index(key)
new = pd.read_excel(updated_version).set_index(key)
added = new.loc[new.index.difference(old.index)]
removed = old.loc[old.index.difference(new.index)]
common = old.index.intersection(new.index)
changed = new.loc[common].compare(old.loc[common])
In my test with nine rows against eight, this returned two added people, one removed person, and the two people in both sheets whose first name or arrival date had changed. Check that the key really is unique first: old.index.is_unique must be True in both sheets, or compare fails. The example files have no ID column, so last name stands in for one here; in real data, names repeat.
Highlight the rows
To mark the new and changed rows in the updated workbook, take the right_only rows from the merge, turn their pandas index into Excel row numbers, and color those rows. pandas counts from 0 and the data starts in Excel row 2 below the header, so each index gets 2 added.
# Show only the rows we want to highlight
df_highlight = df_diff.query("Exist == 'right_only'")
# Get the row numbers we want to highlight in Excel
highlight_rows = [int(row) for row in df_highlight["index"].tolist()]
# pandas index starts at 0
# Excel data (w/o header) starts from row 2
first_row_in_excel = 2
highlight_rows = [x + first_row_in_excel for x in highlight_rows]
with xw.App(visible=False) as app:
updated_wb = app.books.open(updated_version)
updated_ws = updated_wb.sheets(1)
rng = updated_ws.used_range
# Highlight the rows in Excel
for row in rng.rows:
if row.row in highlight_rows:
row.color = (255, 71, 76) # light red
updated_wb.save(Path.cwd() / "Different_Shape" / "Difference_Highlighted.xlsx")
The script saves a new file, so the original stays untouched. The openpyxl equivalent of the xlwings block, using the same red fill as above:
wb = load_workbook(updated_version)
ws = wb.active
for row_number in highlight_rows:
for cell in ws[row_number]:
cell.fill = red
wb.save(Path.cwd() / "Different_Shape" / "Difference_Highlighted.xlsx")
Troubleshooting
Most comparison errors come from labels that do not match, or from values that look equal in Excel but have different types in Python.
- ValueError: Can only compare identically-labeled (both index and columns) DataFrame objects. The two DataFrames differ in their rows or their columns. Different row counts: use the merge or the key column method above. Different columns: compare only the columns both sheets share with
cols = df_initial.columns.intersection(df_update.columns)anddf_update[cols].compare(df_initial[cols]), and list the extra columns withdf_update.columns.difference(df_initial.columns). - Rows show up as different although they look the same. Typical causes are a number stored as text in one file (
"1001"against1001), trailing spaces, or a date in one file and date text in the other. Clean both sides the same way before comparing, for example withdf[col].astype(str).str.strip(). - The highlighted rows are off by one or more. The header is not in row 1, or there are empty rows above the data. Set
first_row_in_excelto the Excel row of the first data row. - xlwings fails to start Excel. xlwings needs a desktop Excel on Windows or Mac. Use the openpyxl versions instead.
- The comment line fails on a cell that already has a comment. Excel allows one comment per cell. Delete the old comment first, or skip the
AddCommentline.
Without code
If you only need the answer and not a script, a browser tool or an Excel formula is faster than setting up Python.
My free Excel Compare tool compares two files in your browser and shows what changed, what is new and what is missing. Your files never leave your browser. For two plain lists, use Compare Two Lists.
To stay in Excel, comparing two Excel files without code shows the XLOOKUP-by-ID method and the Table Compare add-in. All of these methods only pair rows whose keys match exactly. If the same customer is spelled two ways in the two sheets, fuzzy matching is what pairs them.
