如何通过Python批量合并excle表格内容(完整代码)

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}")

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值