Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Python Script to Compare Two Excel Sheets: How-To

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

You can compare two Excel sheets with a short Python script that reads both files using pandas, aligns them by a key column, and reports differences cell by cell. The quickest working approach is: load each sheet with pandas.read_excel(), merge on a shared identifier, then flag rows where values differ. This guide walks through a complete, reusable script and the practical details that make the output trustworthy.

What You'll Need

  • Python 3.8 or newer installed on your computer.
  • The pandas and openpyxl libraries. Install them in a terminal with pip install pandas openpyxl. For older .xls files you also need xlrd.
  • The two Excel workbooks you want to compare, ideally with the same column headers and at least one shared identifier column such as an ID, SKU, or email.
  • A code editor or IDE such as VS Code, or a Jupyter notebook.

Step-by-Step

  1. Put both files in one folder. Create a project folder and place the two workbooks there, for example old.xlsx and new.xlsx. Note the exact sheet names inside each workbook; you will pass them to pandas.
  2. Open your editor and create a new file named compare_excel.py in that folder.
  3. Import the libraries and load the sheets. Write:
    import pandas as pd
    
    df_old = pd.read_excel("old.xlsx", sheet_name="Sheet1")
    df_new = pd.read_excel("new.xlsx", sheet_name="Sheet1")
    If you omit sheet_name, pandas reads the first sheet only. Use the exact sheet name shown in Excel's tab.
  4. Check that the columns match. Add print(df_old.columns.tolist()) and print(df_new.columns.tolist()) and run the script. If the column names differ, rename them before comparing, for example df_new = df_new.rename(columns={"Old Name": "New Name"}). Comparing mismatched headers produces misleading results.
  5. Choose a key column. Pick a column that uniquely identifies each row, such as ID. Confirm it is unique in both sheets with df_old["ID"].is_unique. If it is not unique, the merge will create duplicate combinations and inflate the differences.
  6. Merge the two DataFrames on the key. Write:
    merged = df_old.merge(df_new, on="ID", how="outer", suffixes=("_old", "_new"), indicator=True)
    The indicator=True column tells you whether a row exists only in the old file, only in the new file, or in both.
  7. Find added and removed rows. Rows with _merge == "left_only" are missing from the new file; right_only rows are new additions. Print those subsets so you can review them.
  8. Compare cell values for shared rows. For each column present in both sheets, compare the old and new versions. A compact loop:
    shared = merged[merged["_merge"] == "both"]
    for col in df_old.columns:
        if col == "ID" or col not in df_new.columns:
            continue
        diff = shared[shared[col + "_old"] != shared[col + "_new"]]
        if not diff.empty:
            print(col, len(diff), "differences")
            print(diff[["ID", col + "_old", col + "_new"]])
    This prints the ID and both values for every changed cell.
  9. Handle blanks and type mismatches. Excel often stores numbers as text or leaves blanks as NaN. Before comparing, normalise both frames: strip whitespace with df[col] = df[col].astype(str).str.strip() for text columns, and use pd.to_numeric(..., errors="coerce") for numeric ones. Decide whether a blank and a zero should count as different; by default they will.
  10. Write the differences to a new Excel file. Collect each diff DataFrame into a list and save with pd.concat(diffs).to_excel("differences.xlsx", index=False). This gives you a reviewable report instead of scrolling through console output.
  11. Run the script and review the report. Open differences.xlsx and confirm the flagged rows match what you expect. If the count looks too high, revisit step 9; type mismatches are the most common cause of false positives.

Common Mistakes

  • Comparing without a unique key. Merging on a column with duplicates multiplies rows and creates phantom differences.
  • Ignoring hidden whitespace. "ABC" and "ABC " look identical in Excel but compare as different in Python. Strip strings before comparing.
  • Mixing data types. A number stored as text in one sheet and as a number in the other will always show as a difference unless you convert both.
  • Reading only the first sheet. If your data lives on a later tab, pass the correct sheet_name or you will compare empty or wrong data.
  • Forgetting that formulas are read as values. pandas reads the calculated result, not the formula text. If you need to compare formulas themselves, use openpyxl directly.

Tips

  • Keep a copy of both original files before running anything that writes output, so you can always re-run from a clean state.
  • Sort both DataFrames by the key column before merging; it makes the output easier to read.
  • For large files, compare only the columns you care about rather than every column; it speeds up the script and reduces noise.
  • Save the difference report with a timestamp in the filename so repeated runs do not overwrite earlier results.
  • If you compare the same pair of files regularly, wrap the logic in a function that accepts file paths and sheet names as arguments.

Troubleshooting

  • FileNotFoundError: The script is running from a different folder than the workbooks. Use absolute paths or run the script from the folder containing the files.
  • KeyError on a column name: The column name has a trailing space, different capitalisation, or does not exist in that sheet. Print df.columns.tolist() to see the exact names.
  • Every row shows as different: Check data types and whitespace first. Also confirm you merged on the right key and that the key values are formatted identically in both files.
  • Merge produces far more rows than expected: The key column is not unique. Either deduplicate or choose a different key.
  • Excel file will not open after saving: The output path may be open in Excel already, or the file is locked. Close it and re-run.
  • Dates compare as different when they look the same: One sheet may store dates as text. Convert both with pd.to_datetime(..., errors="coerce") before comparing.

Frequently Asked Questions

Can I compare two sheets in the same workbook?

Yes. Pass the workbook path twice with different sheet_name values, for example pd.read_excel("book.xlsx", sheet_name="Jan") and pd.read_excel("book.xlsx", sheet_name="Feb").

Do I need to install Excel to run the script?

No. pandas and openpyxl read the file format directly; Excel does not need to be installed.

Will the script detect formatting changes such as colours or bold text?

No. pandas reads cell values only. To compare formatting you need openpyxl and additional code that inspects cell styles.

How do I compare more than two files at once?

Loop over the file paths, compare each one against a baseline file, and append the results to a list before saving a combined report.

What if the two sheets have different column orders?

Column order does not matter for the merge, but the column names must match. Rename columns so the names align before comparing.

Can I run this on a Mac?

Yes. The same Python and pandas commands work on Windows, macOS, and Linux; only the terminal commands for installing packages may differ slightly.