要在比较中仅输出不同项的单元格内的差异内容,可以将差异的部分提取出来并输出。对于字符串和数字,这可能需要不同的处理方式。以下是一个更新的版本,旨在输出存在差异的单元格内的详细差异:
python
import pandas as pd
def extract_difference(value1, value2):
# 简单的比较例子,仅适用于字符串
if isinstance(value1, str) and isinstance(value2, str):
# 找到不一样的字符
diff = ''.join([c1 if c1 != c2 else "" for c1, c2 in zip(value1, value2)])
if len(value1) != len(value2):
diff += value2[len(value1):] if len(value2) > len(value1) else value1[len(value2):]
return diff
elif isinstance(value1, (int, float)) and isinstance(value2, (int, float)):
return abs(value1 - value2)
return f"Difference in type: {type(value1)} vs {type(value2)}"
def compare_excel(file1, file2, key_column, sheet_name=0):
# 读取两个 Excel 文件
df1 = pd.read_excel(file1, sheet_name=sheet_name)
df2 = pd.read_excel(file2, sheet_name=sheet_name)
# 将比较列设为索引,以便于比较
df1.set_index(key_column, inplace=True)
df2.set_index(key_column, inplace=True)
# 找到所有的行的并集
all_keys = df1.index.union(df2.index)
# 储存差异信息
diff_list = []
for key in all_keys:
if key not in df1.index:
# 如果该行在 df1 中缺失
diff_list.append({
"ID": key,
"Status": "Missing in File 1",
"Column": "N/A",
"Value in File 1": "N/A",
"Value in File 2": df2.loc[key].to_dict(),
"Difference": df2.loc[key].to_dict()
})
elif key not in df2.index:
# 如果该行在 df2 中缺失
diff_list.append({
"ID": key,
"Status": "Missing in File 2",
"Column": "N/A",
"Value in File 1": df1.loc[key].to_dict(),
"Value in File 2": "N/A",
"Difference": df1.loc[key].to_dict()
})
else:
# 对比相同的索引行
row1 = df1.loc[key]
row2 = df2.loc[key]
for col in df1.columns:
value1, value2 = row1[col], row2[col]
# 忽略比较中都为空的单元格
if pd.isna(value1) and pd.isna(value2):
continue
if value1 != value2:
diff_content = extract_difference(value1, value2)
diff_list.append({
"ID": key,
"Status": "Different Value",
"Column": col,
"Value in File 1": value1,
"Value in File 2": value2,
"Difference": diff_content
})
# 将差异输出为 DataFrame
diff_df = pd.DataFrame(diff_list)
return diff_df
# 用例
file1 = 'example1.xlsx'
file2 = 'example2.xlsx'
key_column = 'ID' # 假设每一行都有一个名为 'ID' 的唯一标识符
diffs = compare_excel(file1, file2, key_column)
print(diffs)
# 可选:将差异写入新的 Excel 文件
diffs.to_excel('diff_output.xlsx', index=False)