如何用Pandas将多Excel文件的独立工作表合并到一个工作簿?
保留原工作表结构合并多Excel文件到单个工作簿
以下是实现需求的代码,会将当前目录下所有.xls/.xlsx文件的所有工作表,保留原名称和数据结构,合并到同一个输出工作簿中:
import os import pandas as pd print("合并多Excel文件的所有工作表到单个工作簿") cwd = os.path.abspath('') files = os.listdir(cwd) # 创建输出目录(如果不存在) os.makedirs('Combined', exist_ok=True) # 使用ExcelWriter批量写入多个工作表 with pd.ExcelWriter('Combined/FinalWorkbook.xlsx', engine='openpyxl') as writer: for file in files: # 只处理Excel格式文件 if file.endswith(('.xls', '.xlsx')): # 跳过输出文件本身,避免循环读取 if os.path.join(cwd, file) == os.path.join(cwd, 'Combined/FinalWorkbook.xlsx'): continue excel_file = pd.ExcelFile(file) sheets = excel_file.sheet_names for sheet in sheets: print(f"处理中: {file} -> {sheet}") # 读取工作表,保留原结构 df = excel_file.parse(sheet_name=sheet) # 写入工作表,使用原名称,不添加索引列 df.to_excel(writer, sheet_name=sheet, index=False) print("合并完成!") input("按回车键退出...")
关键改动说明
- 使用
pd.ExcelWriter作为上下文管理器,一次性创建并写入目标工作簿,比多次创建文件更高效 - 添加了
os.makedirs('Combined', exist_ok=True)确保输出目录存在,避免报错 - 跳过输出的目标文件,防止程序循环读取自己生成的文件
index=False参数避免写入时自动添加索引列,严格保留原工作表的行列结构
可选:处理重复工作表名称
如果不同文件中有重名的工作表,可以添加逻辑给重复名称加后缀,避免覆盖:
import os import pandas as pd print("合并多Excel文件的所有工作表到单个工作簿") cwd = os.path.abspath('') files = os.listdir(cwd) os.makedirs('Combined', exist_ok=True) existing_sheet_names = [] with pd.ExcelWriter('Combined/FinalWorkbook.xlsx', engine='openpyxl') as writer: for file in files: if file.endswith(('.xls', '.xlsx')): if os.path.join(cwd, file) == os.path.join(cwd, 'Combined/FinalWorkbook.xlsx'): continue excel_file = pd.ExcelFile(file) sheets = excel_file.sheet_names for sheet in sheets: print(f"处理中: {file} -> {sheet}") df = excel_file.parse(sheet_name=sheet) # 处理重复表名 final_sheet_name = sheet counter = 1 while final_sheet_name in existing_sheet_names: final_sheet_name = f"{sheet}_{counter}" counter += 1 existing_sheet_names.append(final_sheet_name) df.to_excel(writer, sheet_name=final_sheet_name, index=False) print("合并完成!") input("按回车键退出...")
内容的提问来源于stack exchange,提问作者pythonist
相关产品推荐
相关产品推荐

