使用Python批量合并多个Excel文件的代码实现
更新时间:2025年12月22日 09:14:29 作者:LucaTech
本文介绍如何使用Python批量合并多个Excel文件,通过定义函数,可以轻松地将指定文件夹内的所有Excel文件整合到一个文件中,并提供了按文件名提取日期信息及按原文件名区分Sheet的方法,需要的朋友可以参考下
适用场景
当你有多个列名一致的excel文件的时候,你想要把多个excel文件合并成一个excel文件
Python代码实现
- 首先导入需要的库
import pandas as pd import os
- 将所有需要合并的excel放进一个单独的文件夹里
- 定义一个函数
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
一些说明
- 上面的代码中root是就是当前文件夹的所有路径
- files是一个list, 包含文件夹中所有excel的名称
- 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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Python调用DeepSeek API查询ClickHouse的流程步骤
本文介绍如何利用DeepSeek API和ClickHouse构建自然语言查询数据库,文章详细说明了环境配置步骤,包括Python安装、必备库安装、DeepSeek API Key获取和ClickHouse连接配置,需要的朋友可以参考下2026-03-03
Python实现多图片格式(PNG/JPG/SVG)到幻灯片的批量转换
这篇文章主要介绍了Python实现多图片格式(PNG/JPG/SVG)到幻灯片的批量转换,这篇文章将详细介绍如何使用 Python 将各种图片转换为 PPT 幻灯片,需要的可以了解下2025-11-11
利于python脚本编写可视化nmap和masscan的方法
这篇文章主要介绍了利于python脚本编写可视化nmap和masscan的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2020-12-12


最新评论