import pandas as pd
import os
import sys
from tqdm import tqdm # 进度条库
# 检查命令行参数,允许用户输入路径
if len(sys.argv) > 1:
excel_directory = sys.argv[1]
else:
excel_directory = input("")#替换为自己路径
# 检查目录是否存在
if not os.path.exists(excel_directory):
raise FileNotFoundError(f"目录 {excel_directory} 不存在,请检查路径。")
# 用于存储合并后的数据的 DataFrame
combined_df = pd.DataFrame()
# 遍历目录下的所有 Excel 文件并合并,增加进度条显示
excel_files = [f for f in os.listdir(excel_directory) if f.endswith(('.xlsx', '.xls'))]
if not excel_files:
raise FileNotFoundError(f"在目录 {excel_directory} 中未找到 Excel 文件。")
# 增加进度条并捕获可能的错误
for filename in tqdm(excel_files, desc="合并 Excel 文件中"):
try:
file_path = os.path.join(excel_directory, filename)
df = pd.read_excel(file_path)
combined_df = pd.concat([combined_df, df], ignore_index=True)
except Exception as e:
print(f"读取文件 {filename} 时出错: {e}")
# 指定输出文件路径
output_file_path = os.path.join(excel_directory, 'combined_excel.xlsx')
# 将合并后的数据写入新的 Excel 文件
try:
combined_df.to_excel(output_file_path, index=False)
print(f"合并完成,结果保存在 {output_file_path}")
except Exception as e:
print(f"保存合并文件时出错: {e}")