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__": user_path = input("> ").strip() merge_excel_files(user_path)