import pandas as pd
import tkinter as tk
from tkinter import filedialog, messagebox
import os
def select_file(var):
"""打开文件对话框,让用户选择文件"""
filename = filedialog.askopenfilename(filetypes=[("Excel files", "*.xls;*.xlsx")])
if filename:
var.set(filename)
def compare_excel_files():
"""比较两个 Excel 文件的所有工作表并输出差异"""
file1 = file_path1.get()
file2 = file_path2.get()
if not file1 or not file2:
messagebox.showwarning("警告", "请确保选择了两个文件")
return
differences = []
try:
# 读取 Excel 文件的所有工作表
xls1 = pd.ExcelFile(file1)
xls2 = pd.ExcelFile(file2)
# 对比每个工作表
for sheet_name in xls1.sheet_names:
if sheet_name in xls2.sheet_names:
df1 = pd.read_excel(file1, sheet_name=sheet_name)
df2 = pd.read_excel(file2, sheet_name=sheet_name)
# 比较数据
diff = pd.concat([df1, df2]).drop_duplicates(keep=False)
if not diff.empty:
differences.append(f"工作表 '{sheet_name}' 的差异:\n{diff.to_string(index=False)}\n")
else:
differences.append(f"工作表 '{sheet_name}' 在第二个文件中不存在。\n")
# 输出结果到文本文件
output_file = 'differences.txt'
with open(output_file, 'w', encoding='utf-8') as f:
if differences:
f.write("\n".join(differences))
else:
f.write("两个文件之间没有差异。\n")
messagebox.showinfo("完成", f"比较完成,结果已输出到 {os.path.abspath(output_file)}")
except Exception as e:
messagebox.showerror("错误", f"在处理文件时发生错误: {e}")
# 创建主窗口
root = tk.Tk()
root.title("Excel 工作表对比工具")
file_path1 = tk.StringVar()
file_path2 = tk.StringVar()
# 文件1选择按钮
tk.Label(root, text="选择第一个 Excel 文件:").pack(pady=5)
tk.Entry(root, textvariable=file_path1, width=50).pack(pady=5)
tk.Button(root, text="浏览", command=lambda: select_file(file_path1)).pack(pady=5)
# 文件2选择按钮
tk.Label(root, text="选择第二个 Excel 文件:").pack(pady=5)
tk.Entry(root, textvariable=file_path2, width=50).pack(pady=5)
tk.Button(root, text="浏览", command=lambda: select_file(file_path2)).pack(pady=5)
# 对比按钮
tk.Button(root, text="对比文件", command=compare_excel_files).pack(pady=20)
# 启动 GUI
root.mainloop()
按照插件
pip install pandas openpyxl xlrd