分为两种合并方式:
1、合并同一目录下多个excel,每个excel都只有1个sheet页
2、合并同一excel里的多个sheet页
一、合并同一目录下多个excel,每个excel都只有1个sheet页
#合并excel,每个excel只有一个表单
import pandas as pd
import os
target_path = r'F:\pythonTest\合并excel'
df_list = []
for path,dirs,files in os.walk(target_path ):
# path 表示当前正在访问的文件夹路径
# dirs 表示该文件夹下的子目录名list
# files 表示该文件夹下的文件list
# 遍历文件
for file in files:
file_path = os.path.join(path,file)
df = pd.read_excel(file_path)
df_list.append(df)
merged_df = pd.concat(df_list)
#print(result)
merged_df.to_excel(r'F:\pythonTest\合并excel\result.xlsx',index=False)
二、合并同一excel里的多个sheet页
增加了“表单”列,用于区分每行来自有哪个表单
#合并同一个excel中的多个sheet页
import pandas as pd
df=pd.read_excel(r'F:\pythonTest\合并excel-sheet\Python合并sheet页测试表.xlsx',sheet_name=None)#读取excel所有sheet数据
#查看所有sheet名
#print(df.keys())
#添加 表单 列,显示数据来源表单名
for i in df.keys():
df[i]['表单']=i
# 将多个数据框合并到一个数据框中
merged_df = pd.concat(df)
# 将合并后的数据框写入一个新的Excel文件
merged_df.to_excel(r'F:\pythonTest\合并excel-sheet\result.xlsx', index=False)