Smart Systems for Home

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

Compare Two Excel Sheets with Python: Step-by-Step

· 6 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

Comparing two Excel sheets with Python means loading both files into a DataFrame, aligning them on a key column (or on row and column position), and then checking cell by cell for differences. The shortest working version uses pandas: read both sheets with pd.read_excel(), merge them on a shared identifier, and compare the overlapping columns. This guide walks through that process, plus how to write the differences back to a new Excel file so you can review them.

What You'll Need

  • Python 3 installed (any recent version works).
  • The pandas library, plus openpyxl for reading and writing .xlsx files. Install both with pip install pandas openpyxl.
  • Two Excel workbooks (or two sheets in one workbook) that you want to compare.
  • A basic understanding of Python variables and functions.

If you are comparing .xls files (the older format), you also need xlrd, but openpyxl covers .xlsx, which is what most people use today.

Step-by-Step

  1. Install the libraries. Open a terminal or command prompt and run pip install pandas openpyxl. If you use a virtual environment, activate it first. Confirm the install with python -c "import pandas; print(pandas.__version__)".
  2. Load both sheets into DataFrames. Create a Python script and read each file. For example:
    import pandas as pd
    
    df1 = pd.read_excel('file1.xlsx', sheet_name='Sheet1')
    df2 = pd.read_excel('file2.xlsx', sheet_name='Sheet1')
    If the sheets have different names, adjust sheet_name accordingly. You can also pass sheet_name=None to read all sheets into a dictionary.
  3. Inspect the structure. Print df1.head() and df2.head(), and check df1.columns and df2.columns. Make sure the column names match exactly (including spaces and capitalization). If they differ, rename them with df2.rename(columns={'OldName': 'NewName'}, inplace=True).
  4. Choose a comparison key. Decide whether rows should be matched by a unique ID column (like an order number or employee ID) or by position. Matching by key is safer because it handles rows that were inserted or reordered. If you have no key, you can add one with df1['row_id'] = range(len(df1)) and the same for df2, but be aware that this only compares row 1 to row 1, row 2 to row 2, and so on.
  5. Merge the two DataFrames. Use an outer merge on the key column so you can see rows that exist in one file but not the other:
    merged = df1.merge(df2, on='ID', how='outer', suffixes=('_file1', '_file2'), indicator=True)
    The indicator=True adds a _merge column that tells you whether each row is in both, only in file1, or only in file2.
  6. Find rows that exist in only one file. Filter with merged[merged['_merge'] != 'both']. These are added or removed records. You can save them to a separate sheet for review.
  7. Compare matching rows cell by cell. For rows present in both, loop over the shared columns (excluding the key and the _merge column) and compare the _file1 and _file2 versions. A simple approach:
    for col in shared_columns:
        diff = merged[merged[col + '_file1'] != merged[col + '_file2']]
        if not diff.empty:
            print(f'Differences in {col}:')
            print(diff[['ID', col + '_file1', col + '_file2']])
    This prints the ID and the two values for every mismatch. You can collect these into a list of DataFrames and concatenate them later.
  8. Handle missing values carefully. NaN values do not compare equal to each other with != (NaN != NaN is True), which can produce false differences. Use df1[col].fillna('') and the same for df2 before comparing, or use pandas.testing.assert_frame_equal for a strict check that treats NaNs as equal in the same positions.
  9. Write the results to an Excel file. Use pd.ExcelWriter to save a report with one sheet for added rows, one for removed rows, and one for changed cells:
    with pd.ExcelWriter('comparison_report.xlsx') as writer:
        added.to_excel(writer, sheet_name='Added', index=False)
        removed.to_excel(writer, sheet_name='Removed', index=False)
        changes.to_excel(writer, sheet_name='Changed', index=False)
    Open the report in Excel to review and share it.
  10. Run and verify. Execute the script with python compare.py. Check that the report contains the differences you expect. If the report is empty but you know there are differences, revisit the key column and data types (see Common Mistakes).

Common Mistakes

  • Comparing columns with different data types. A number stored as text in one file and as a number in the other will look different. Convert both to the same type with astype(str) or pd.to_numeric before comparing.
  • Ignoring whitespace and case. 'Apple' and 'apple ' are different strings. Strip whitespace with .str.strip() and optionally lowercase both sides if case does not matter.
  • Using a non-unique key. If the ID column has duplicates, the merge will create a cartesian product and produce many false matches. Check for duplicates with df['ID'].duplicated().any() and clean them first.
  • Forgetting that Excel stores dates as serial numbers. pandas usually converts them to datetime objects, but if one file has text dates, they will not match. Parse both with pd.to_datetime.
  • Assuming row order is the same. Always merge on a key rather than relying on position unless you are certain the rows are in the same order.

Tips

  • Use df.equals(other_df) for a quick True/False check of whether two DataFrames are identical (same shape, same values, same index). It is fast and useful as a first pass.
  • For large files, read only the columns you need with usecols to speed things up.
  • Round floating-point numbers before comparing (for example, round(2)) to avoid tiny precision differences.
  • Keep a copy of the original files before running any script that writes output, so you can always start over.
  • If you compare the same pair of files regularly, wrap the logic in a function that takes two file paths and returns the report path.

Troubleshooting

If the script fails with a ModuleNotFoundError, the library is not installed in the Python environment you are running. Run pip install pandas openpyxl again and check that your IDE is using the same interpreter.

If you get a KeyError on the merge, the key column name is misspelled or has leading/trailing spaces. Print the column lists and compare them character by character.

If the comparison report shows every row as different, check data types and whitespace first. A common cause is that one file was saved as CSV and re-opened in Excel, turning numbers into text.

If Excel cannot open the output file, make sure you closed any previous version of the report before running the script, and that the file extension is .xlsx.

If the merge produces far more rows than either input, the key is not unique. Remove duplicates or choose a different key.

Frequently Asked Questions

Can I compare two sheets in the same workbook?

Yes. Read each sheet separately with pd.read_excel('workbook.xlsx', sheet_name='Sheet1') and sheet_name='Sheet2', then follow the same steps.

Do I need to install Excel to run this?

No. pandas and openpyxl read and write .xlsx files directly; Excel itself is not required.

How do I compare formulas rather than values?

pandas reads calculated values by default. To compare formulas, you would need a library that exposes the formula string, such as openpyxl with data_only=False, but that is more advanced and not covered by the simple merge approach.

What if the two sheets have different column names?

Rename one set of columns to match the other before merging, using df.rename(columns={...}). Then proceed as normal.

Can I highlight differences in the original Excel file?

Yes, but it requires writing conditional formatting with openpyxl after saving the report. A simpler approach is to output a separate report file, as shown in the steps.

Is there a built-in pandas function to compare two DataFrames?

pandas.testing.assert_frame_equal raises an error if they differ, and df.compare(other) returns a DataFrame showing differing cells. Both are useful for quick checks, but the merge method gives you more control over keys and added/removed rows.