Python 合并excel

文章讲述了如何用Pythonpandas处理,将单个Excel文件内的单个Sheet和多个Sheet进行合并,同时在合并后添加表单标识。
摘要由CSDN通过智能技术生成

分为两种合并方式:

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)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值