当前位置: 代码网 > it编程>前端脚本>Python > 使用Python批量合并多个Excel文件的代码实现

使用Python批量合并多个Excel文件的代码实现

2025年12月22日 Python 我要评论
适用场景当你有多个列名一致的excel文件的时候,你想要把多个excel文件合并成一个excel文件python代码实现首先导入需要的库import pandas as pdimport os将所有需

适用场景

当你有多个列名一致的excel文件的时候,你想要把多个excel文件合并成一个excel文件

python代码实现

  1. 首先导入需要的库
import pandas as pd
import os
  1. 将所有需要合并的excel放进一个单独的文件夹里
  2. 定义一个函数
def append(path): #path:所有需要合并的excel文件所在的文件夹
    filename_excel = [] # 建立一个空list,用于储存所有需要合并的excel名称
    frames = [] # 建立一个空list,用于储存dataframe
    for root, dirs, files in os.walk(path):
        for file in files:
        	file_with_path = os.path.join(root, file) 
            filename_excel.append(file_with_path)
            df = pd.read_excel(file_with_path)
            frames.append(df)
    df = pd.concat(frames, axis=0)
    return df

一些说明

  1. 上面的代码中root是就是当前文件夹的所有路径
  2. files是一个list, 包含文件夹中所有excel的名称
  3. os.path.join(root, file)就是合并文件夹的路径和文件名称,这样后面的pd.read_excel()就能读取excel文件

tips

也可以不定义函数直接用:

filename_excel = [] 
frames = [] 
for root, dirs, files in os.walk(path):
    for file in files:
        file_with_path = os.path.join(root, file) 
        filename_excel.append(file_with_path)
        df = pd.read_excel(file_with_path)
        frames.append(df)
df = pd.concat(frames, axis=0)
df.to_excel("合并的excel.xlsx")

特殊情况

如果excel的文件名包括日期,且需要写到最后汇总的excel中

def append(path): 
    filename_excel = []
    frames = [] 
    for root, dirs, files in os.walk(path):
        for file in files:
        	file_with_path = os.path.join(root, file) 
            filename_excel.append(file_with_path)
            df = pd.read_excel(file_with_path)
            # 将文件名中包含的日期信息写入dataframe
            df["日期"] = pd.to_datetime(file.strip('.xls')[-1:])#日期在什么位置需要自己调整
            frames.append(df)
    df = pd.concat(frames, axis=0)
    return df

如果将多个excel合并到一个excel中,sheet命名为excel的名字

def combine(path):
    with pd.excelwriter("合并的excel.xlsx") as writer:
        for root, dirs, files in os.walk(path):
            for file in files:
                filename = os.path.join(root, file)
                df = pd.read_excel(filename)
                df.to_excel(writer, sheet_name=file.strip('.xls')) #删除文件名的后缀,有时候是.csv/.xlsx
        return df

到此这篇关于使用python批量合并多个excel文件的代码实现的文章就介绍到这了,更多相关python合并多个excel内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com