From 4a43fbc895ff2f82d1cf3b1a2361a76b2671e133 Mon Sep 17 00:00:00 2001 From: betterbeast2023 Date: Mon, 8 Jun 2026 06:41:26 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E8=84=9A=E6=9C=AC=20?= =?UTF-8?q?`merge=5Ftransactions.py`=20=E7=94=A8=E4=BA=8E=E5=90=88?= =?UTF-8?q?=E5=B9=B6=E6=8C=87=E5=AE=9A=E7=9B=AE=E5=BD=95=E4=B8=8B=E7=9A=84?= =?UTF-8?q?=20Excel=20=E6=96=87=E4=BB=B6=E4=B8=AD=E7=9A=84=E2=80=9C?= =?UTF-8?q?=E4=BA=A4=E6=98=93=E6=B5=81=E6=B0=B4=E2=80=9D=E5=B7=A5=E4=BD=9C?= =?UTF-8?q?=E8=A1=A8=EF=BC=8C=E5=B9=B6=E8=BE=93=E5=87=BA=E5=88=B0=E5=90=8C?= =?UTF-8?q?=E4=B8=80=E7=9B=AE=E5=BD=95=E4=B8=8B=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: aider (ollama/gemma4:12b) --- merge_transactions.py | 59 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 merge_transactions.py diff --git a/merge_transactions.py b/merge_transactions.py new file mode 100644 index 0000000..7573825 --- /dev/null +++ b/merge_transactions.py @@ -0,0 +1,59 @@ +import os +import pandas as pd +import glob + +def merge_excel_files(input_dir): + # 获取绝对路径并确保它是存在的 + input_dir = os.path.abspath(input_dir) + if not os.path.isdir(input_dir): + print(f"错误:路径 '{input_dir}' 不是有效的目录。") + return + + # 获取目录下所有的 excel 文件 + # 支持 .xlsx 和 .xls 格式 + file_pattern = os.path.join(input_dir, "*.xls*") + files = glob.glob(file_pattern) + + all_data = [] + target_sheet = "交易流水" + + for file_path in files: + # 跳过输出文件本身,防止循环读取 + if "txn_summary" in os.path.basename(file_path): + continue + + try: + # 加载 Excel 文件 + # 使用 ExcelFile 对象可以先检查 sheet 名称是否存在 + xls = pd.ExcelFile(file_path) + if target_sheet in xls.sheet_names: + df = pd.read_excel(xls, sheet_name=target_sheet) + # 记录来源文件名(可选,方便核对) + df['source_file'] = os.path.basename(file_path) + all_data.append(df) + print(f"成功读取: {os.path.basename(file_path)}") + else: + print(f"跳过文件 {os.path.basename(file_path)}: 未找到名为 '{target_sheet}' 的工作表。") + except Exception as e: + print(f"处理文件 {os.path.basename(file_path)} 时出错: {e}") + + if all_data: + # 合并所有 DataFrame + merged_df = pd.concat(all_data, ignore_index=True) + + # 生成输出路径 + output_path = os.path.join(input_dir, "txn_summary.xlsx") + + # 保存到 Excel + with pd.ExcelWriter(output_path, engine='openpyxl') as writer: + merged_df.to_excel(writer, sheet_name='Summary', index=False) + + print("-" * 30) + print(f"合并完成!结果已保存至: {output_path}") + else: + print("未找到任何包含 '交易流水' 工作表的 Excel 文件。") + +if __name__ == "__main__": + print("请输入包含 Excel 文件的目录路径:") + user_path = input("> ").strip() + merge_excel_files(user_path)