场景描述:
1、将多个excel的指定sheet合并。
2、生成新的合并后的excel文件。
参考文档1:[用Python Pandas合并多个excel(.xlsx)文件]
参考文档2:pandas函数read_excel
import os
import pandas as pd
dir = r'D:\hebing' # 设置待合并文件夹的路径
DFs = []
'''
os.walk会遍历指定的文件夹
每一层遍历:
root保存的就是当前遍历的文件夹的绝对路径;
dirs保存当前文件夹下的所有子文件夹的名称
files保存当前文件夹下的所有文件的名称
'''
for root, dirs, files in os.walk(dir):
for file in files:
file_path = os.path.join(root, file) # 用当前文件夹和文件名组合成一个完整路径
# 填写的sheet_name,header, skipfooter参数。
df = pd.read_excel(file_path, sheet_name=0, header=1, skipfooter=0)
DFs.append(df)
alldata = pd.concat(DFs) # 合并所有数据,将多个DataFrame合并为一个
alldata.to_excel(r'D:\excel合并结果.xlsx', index=False) # index:表示是否写行索引,默认为True