python 多个excel合并

excel是这样的

image

 多个这样的合并

import pandas as pd
import os
import glob


def merge_excel_files_with_source(input_folder, output_file):
    """
    批量合并Excel文件,并添加来源文件列

    Parameters:
    input_folder (str): 包含Excel文件的文件夹路径
    output_file (str): 输出的合并CSV文件路径
    """

    # 查找所有的Excel文件
    excel_patterns = [
        os.path.join(input_folder, "*.xlsx"),
        os.path.join(input_folder, "*.xls")
    ]

    excel_files = []
    for pattern in excel_patterns:
        excel_files.extend(glob.glob(pattern))

    # 排除输出文件本身
    if os.path.abspath(output_file) in [os.path.abspath(f) for f in excel_files]:
        excel_files = [f for f in excel_files if os.path.abspath(f) != os.path.abspath(output_file)]

    if not excel_files:
        print(f"在文件夹 {input_folder} 中未找到任何Excel文件")
        return

    print(f"找到 {len(excel_files)} 个Excel文件")
    print("开始合并...")

    # 存储所有数据的列表
    all_data = []

    # 读取每个Excel文件
    for i, excel_file in enumerate(excel_files, 1):
        try:
            print(f"正在读取: {os.path.basename(excel_file)} ({i}/{len(excel_files)})")

            # 读取Excel文件
            df = pd.read_excel(excel_file)

            # 检查是否包含必要的列
            required_columns = ['ID', 'Row', 'Col', 'SWT']
            if not all(col in df.columns for col in required_columns):
                print(f"  警告: 文件 {os.path.basename(excel_file)} 缺少必要的列,跳过")
                continue

            # 添加来源文件列
            df['Source_File'] = os.path.basename(excel_file)

            # 跳过表头(除了第一个文件)
            if all_data:
                # 对于后续文件,直接添加数据行(跳过第一行表头)
                all_data.append(df.iloc[1:] if len(df) > 1 else df)
            else:
                # 对于第一个文件,包含表头
                all_data.append(df)

        except Exception as e:
            print(f"  读取文件 {os.path.basename(excel_file)} 时出错: {str(e)}")
            continue

    if not all_data:
        print("没有成功读取任何Excel文件")
        return

    # 合并所有数据
    try:
        merged_df = pd.concat(all_data, ignore_index=True)

        # 保存合并后的文件为CSV
        merged_df.to_csv(output_file, index=False, encoding='utf-8-sig')

        print(f"\n合并完成!")
        print(f"总共合并了 {len(merged_df)} 行数据")
        print(f"合并后的文件已保存至: {output_file}")

        # 显示合并后的数据信息
        print(f"\n合并后的数据信息:")
        print(f"列名: {list(merged_df.columns)}")
        print(f"数据形状: {merged_df.shape}")
        print(f"前5行数据预览:")
        print(merged_df.head())

    except Exception as e:
        print(f"合并数据时出错: {str(e)}")


# 使用示例
if __name__ == "__main__":
    # 带来源文件信息的合并
    input_folder = "E:/precipiation_daytime/miniblock/SWT"  # 替换为你的Excel文件所在文件夹
    output_file = "E:/precipiation_daytime/miniblock/one/SWT_merged.csv"  # 合并后的输出CSV文件路径

    print("开始合并Excel文件...")
    merge_excel_files_with_source(input_folder, output_file)

 

posted @ 2025-11-09 16:14  秋刀鱼CCC  Views(4)  Comments(0)    收藏  举报