You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中快速对比Pandas生成的Excel文件(含格式)

解决Pandas生成Excel文件的高效校验问题

为什么filecmp对比会显示不同?

Excel属于OLE复合文档,除了数据内容外,还包含**创建时间、文件唯一标识符(UUID)**等元数据。哪怕数据和格式完全一致,每次用Pandas生成文件时,这些元数据都会自动生成新值,导致filecmp直接对比二进制文件时返回False。

高效校验方案

场景1:仅校验数据内容(不关心格式)

直接用Pandas重新读取文件为DataFrame,利用内置的向量化对比方法,速度远快于遍历单元格:

import pandas as pd

# 读取两个文件的DataFrame
df_output = pd.read_excel("output.xlsx")
df_output2 = pd.read_excel("output2.xlsx")

# 对比数据是否完全一致
print(df_output.equals(df_output2))  # 会返回True

df.equals()会逐行逐列对比所有数据(包括索引和列名),是数据校验最快的方式。

场景2:需要校验数据+格式(单元格样式、列宽等)

使用openpyxl库直接操作Excel的底层结构,优化遍历逻辑,只对比关键属性:

from openpyxl import load_workbook

def compare_excel_with_format(file1, file2):
    # 加载工作簿(data_only=False保留格式信息)
    wb1 = load_workbook(file1, data_only=False)
    wb2 = load_workbook(file2, data_only=False)
    
    # 1. 对比工作表集合
    if set(wb1.sheetnames) != set(wb2.sheetnames):
        return False
    
    for sheet_name in wb1.sheetnames:
        ws1 = wb1[sheet_name]
        ws2 = wb2[sheet_name]
        
        # 2. 对比工作表的行/列范围
        if (ws1.max_row, ws1.max_column) != (ws2.max_row, ws2.max_column):
            return False
        
        # 3. 批量对比单元格值与关键样式
        for row in ws1.iter_rows(min_row=1, max_row=ws1.max_row, min_col=1, max_col=ws1.max_column):
            for cell1 in row:
                cell2 = ws2[cell1.coordinate]
                # 对比单元格值
                if cell1.value != cell2.value:
                    return False
                # 对比核心样式(可根据需求扩展:边框、数字格式等)
                style_attrs1 = (cell1.font.name, cell1.font.size, cell1.fill.start_color.index, cell1.alignment.horizontal)
                style_attrs2 = (cell2.font.name, cell2.font.size, cell2.fill.start_color.index, cell2.alignment.horizontal)
                if style_attrs1 != style_attrs2:
                    return False
        
        # 4. 对比列宽与行高
        for col_letter in ws1.column_dimensions:
            if ws1.column_dimensions[col_letter].width != ws2.column_dimensions[col_letter].width:
                return False
        for row_num in ws1.row_dimensions:
            if ws1.row_dimensions[row_num].height != ws2.row_dimensions[row_num].height:
                return False
    
    return True

# 执行对比
print(compare_excel_with_format("output.xlsx", "output2.xlsx"))

这个方法通过批量迭代单元格、只提取关键格式属性对比,比自定义遍历高效得多,同时覆盖了格式校验需求。

内容的提问来源于stack exchange,提问作者Alberto B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 05:59:53