Python批处理excel文件多个sheet汇总脚本

背景介绍

假设有10个excle表,每个excel包含sheet1,sheet2,sheet3,sheet4,每个excel中sheet1的列名是一样的,sheet2的列名是一样的,现在要做的是将这10个excel中的sheet1合并汇总,sheet2合并汇总,将汇总后的sheet1和sheet2放在汇总表.xlsx里面,补充条件:每个excel的sheet1名字和汇总表的sheet1名字一样,每个excel的sheet2名字和汇总表的sheet2名字一样

目标

要在最终生成的汇总表中移除每个工作表中的’Excel’和’Sheet’两列,你可以在写入汇总数据之前对每个工作表的DataFrame进行处理:

import os
import pandas as pd

def combine_excel_sheets(summary_filename, folder_path, sheet_list):
    # 遍历指定文件夹下的所有Excel文件
    for file in os.listdir(folder_path):
        if file.endswith(".xlsx"):
            file_path = os.path.join(folder_path, file)
            # 读取所有工作表数据
            excel_data = pd.read_excel(file_path, sheet_name=None)

            # 提取指定工作表的数据
            for sheet_name in sheet_list:
                if sheet_name in excel_data:
                    sheet_df = excel_data[sheet_name]
                    # 添加新列标记所属excel文件和所属sheet
                    sheet_df['Excel'] = file
                    sheet_df['Sheet'] = sheet_name
                    globals()[f"{
      
      sheet_name}_df"] = pd.concat([globals().get(f"{
      
      sheet_name}_df", pd.DataFrame()), sheet_df], ignore_index=True)

    # 将汇总数据写入单个Excel文件中
    with pd.ExcelWriter(summary_filename) as writer:
        for sheet_name in sheet_list:
            # 将某个sheet的所有数据筛选出来
            sheet_df = globals().get(f"{
      
      sheet_name}_df", pd.DataFrame())
            # 移除'Excel'和'Sheet'两列
            sheet_df = sheet_df.drop(['Excel', 'Sheet'], axis=1)
            # 将数据写入汇总表格
            sheet_df.to_excel(writer, sheet_name=sheet_name, index=False)

# 指定自定义的汇总表完整路径、文件夹路径和要处理的工作表名称列表
summary_filename = "/path/to/your/summary/my_summary.xlsx"
folder_path = "/path/to/your/folder"
sheet_list = ["Sheet1", "Sheet2"]

# 调用函数进行Excel表格合并
combine_excel_sheets(summary_filename, folder_path, sheet_list)

在上述修改后的代码中,我们在写入每个工作表的数据之前使用drop函数移除了’Excel’和’Sheet’两列,并将更新后的数据写入到汇总的Excel文件中。这样,最终生成的汇总表中将不会包含每个工作表中的’Excel’和’Sheet’两列的信息。

猜你喜欢

转载自blog.csdn.net/m0_57021623/article/details/135231113