对比Excel表格,将差异输出到TXT文本

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值