如何使用 Python 将多个 excel 文件合并为一个文件?
off999 2024-12-17 15:42 24 浏览 0 评论
通常,我们正在处理 Excel 文件,我们肯定遇到过需要将多个 Excel 文件合并为一个文件的情况。传统方法一直是在 excel 中使用 VBA 代码,它可以完成这项工作,但是不太容易理解。另一种方法是手动将长Excel文件复制到一个文件中,这不仅耗时,麻烦,而且容易出错。
使用 python中的Pandas 模块即可轻松快速地完成此任务。如果未安装Pandas模块在终端中使用以下命令:
pip install pandas
1、导入库
import os
import pandas as pd
- os: 用于与操作系统交互,特别是文件和目录操作。
- pandas: 一个强大的Python数据处理库,用于读取和写入Excel文件
2、定义函数
def merge_excel_files(folder_path, output_file):
- folder_path: 包含要合并的Excel文件的文件夹路径。
- output_file: 保存合并数据的输出文件名。
3、列出Excel文件
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')
- 这行代码列出了指定文件夹中所有扩展名为.xlsx或.xls的文件。
4、读取并合并Excel文件
data_frames = []
for file in excel_files:
file_path = os.path.join(folder_path, file)
try:
data = pd.read_excel(file_path)
data_frames.append(data)
except Exception as e:
print(f"读取文件 {file} 时出错: {e}")
- 创建一个空的列表data_frames来存储每个Excel文件的数据。
- 脚本遍历每个Excel文件,将其内容读取到一个DataFrame中,并将其追加到data_frames列表中。
- 如果读取文件时发生错误,会打印错误信息。
5、合并数据
merged_data = pd.concat(data_frames, ignore_index=True)
- 使用pd.concat函数将所有DataFrame对象合并成一个DataFrame,并忽略索引。
6、保存合并后的数据
merged_data.to_excel(output_file, index=False)
print(f"合并后的文件已保存为 {output_file}")
- 将合并后的数据保存到指定的输出文件中,不包括索引。
- 打印一条消息,确认文件已保存。
7、错误处理
except Exception as e:
print(f"处理文件夹 {folder_path} 时出错: {e}")
- 如果在处理文件夹或合并数据时发生错误,会打印错误信息。
8、使用示例
folder_path = 'C:/Users/standee/Desktop/test'
output_file = 'merged_excel.xlsx'
merge_excel_files(folder_path, output_file)
- 这部分脚本设置文件夹路径和输出文件名,然后调用merge_excel_files函数执行合并。
完整代码如下:
import os
import pandas as pd
def merge_excel_files(folder_path, output_file):
try:
# 获取文件夹中的所有Excel文件
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')]
# 读取并合并所有Excel文件
data_frames = []
for file in excel_files:
file_path = os.path.join(folder_path, file)
try:
data = pd.read_excel(file_path)
data_frames.append(data)
except Exception as e:
print(f"读取文件 {file} 时出错: {e}")
# 使用pd.concat合并数据
merged_data = pd.concat(data_frames, ignore_index=True)
merged_data.to_excel(output_file, index=False)
print(f"合并后的文件已保存为 {output_file}")
except Exception as e:
print(f"处理文件夹 {folder_path} 时出错: {e}")
# 使用示例
folder_path = 'C:/Users/standee/Desktop/test'
output_file = 'merged_excel.xlsx'
merge_excel_files(folder_path, output_file)
需合并的数据:
“001.xlsx”
OrderDate | Region | City | Category | Product | Quantity | UnitPrice | TotalPrice |
2020/1/1 | East | Boston | Bars | Carrot | 33 | 1.77 | 58.41 |
2020/1/4 | East | Boston | Crackers | Whole Wheat | 87 | 3.49 | 303.63 |
2020/1/7 | West | Los Angeles | Cookies | Chocolate Chip | 58 | 1.87 | 108.46 |
2020/1/10 | East | New York | Cookies | Chocolate Chip | 82 | 1.87 | 153.34 |
2020/1/13 | East | Boston | Cookies | Arrowroot | 38 | 2.18 | 82.84 |
2020/1/16 | East | Boston | Bars | Carrot | 54 | 1.77 | 95.58 |
2020/1/19 | East | Boston | Crackers | Whole Wheat | 149 | 3.49 | 520.01 |
2020/1/22 | West | Los Angeles | Bars | Carrot | 51 | 1.77 | 90.27 |
2020/1/25 | East | New York | Bars | Carrot | 100 | 1.77 | 177 |
2020/1/28 | East | New York | Snacks | Potato Chips | 28 | 1.35 | 37.8 |
2020/1/31 | East | Boston | Cookies | Arrowroot | 36 | 2.18 | 78.48 |
2020/2/3 | East | Boston | Cookies | Chocolate Chip | 31 | 1.87 | 57.97 |
2020/2/6 | East | Boston | Crackers | Whole Wheat | 28 | 3.49 | 97.72 |
2020/2/9 | West | Los Angeles | Bars | Carrot | 44 | 1.77 | 77.88 |
“002.xlsx”
OrderDate | Region | City | Category | Product | Quantity | UnitPrice | TotalPrice |
2020/3/29 | East | Boston | Cookies | Oatmeal Raisin | 193 | 2.84 | 548.12 |
2020/4/1 | West | Los Angeles | Bars | Carrot | 58 | 1.77 | 102.66 |
2020/4/4 | West | Los Angeles | Snacks | Potato Chips | 68 | 1.68 | 114.24 |
2020/4/7 | East | New York | Bars | Carrot | 91 | 1.77 | 161.07 |
2020/4/10 | East | New York | Crackers | Whole Wheat | 23 | 3.49 | 80.27 |
2020/4/13 | West | San Diego | Snacks | Potato Chips | 28 | 1.68 | 47.04 |
2020/4/16 | East | Boston | Bars | Carrot | 48 | 1.77 | 84.96 |
2020/4/19 | East | Boston | Snacks | Potato Chips | 134 | 1.68 | 225.12 |
2020/4/22 | West | Los Angeles | Bars | Carrot | 20 | 1.77 | 35.4 |
2020/4/25 | East | New York | Bars | Carrot | 53 | 1.77 | 93.81 |
2020/4/28 | East | New York | Snacks | Potato Chips | 64 | 1.68 | 107.52 |
2020/5/1 | West | San Diego | Cookies | Chocolate Chip | 63 | 1.87 | 117.81 |
2020/5/4 | East | Boston | Bars | Bran | 105 | 1.87 | 196.35 |
2020/5/7 | East | Boston | Cookies | Oatmeal Raisin | 138 | 2.84 | 391.92 |
运行Python:
D:\python\python.exe D:\pycharm\pythonProject\excelmerge.py
合并后的文件已保存为 merged_excel.xlsx
Process finished with exit code 0
合并后生成一个merged_excel.xlsx的文件:
OrderDate | Region | City | Category | Product | Quantity | UnitPrice | TotalPrice |
2020/1/1 | East | Boston | Bars | Carrot | 33 | 1.77 | 58.41 |
2020/1/4 | East | Boston | Crackers | Whole Wheat | 87 | 3.49 | 303.63 |
2020/1/7 | West | Los Angeles | Cookies | Chocolate Chip | 58 | 1.87 | 108.46 |
2020/1/10 | East | New York | Cookies | Chocolate Chip | 82 | 1.87 | 153.34 |
2020/1/13 | East | Boston | Cookies | Arrowroot | 38 | 2.18 | 82.84 |
2020/1/16 | East | Boston | Bars | Carrot | 54 | 1.77 | 95.58 |
2020/1/19 | East | Boston | Crackers | Whole Wheat | 149 | 3.49 | 520.01 |
2020/1/22 | West | Los Angeles | Bars | Carrot | 51 | 1.77 | 90.27 |
2020/1/25 | East | New York | Bars | Carrot | 100 | 1.77 | 177 |
2020/1/28 | East | New York | Snacks | Potato Chips | 28 | 1.35 | 37.8 |
2020/1/31 | East | Boston | Cookies | Arrowroot | 36 | 2.18 | 78.48 |
2020/2/3 | East | Boston | Cookies | Chocolate Chip | 31 | 1.87 | 57.97 |
2020/2/6 | East | Boston | Crackers | Whole Wheat | 28 | 3.49 | 97.72 |
2020/2/9 | West | Los Angeles | Bars | Carrot | 44 | 1.77 | 77.88 |
2020/3/29 | East | Boston | Cookies | Oatmeal Raisin | 193 | 2.84 | 548.12 |
2020/4/1 | West | Los Angeles | Bars | Carrot | 58 | 1.77 | 102.66 |
2020/4/4 | West | Los Angeles | Snacks | Potato Chips | 68 | 1.68 | 114.24 |
2020/4/7 | East | New York | Bars | Carrot | 91 | 1.77 | 161.07 |
2020/4/10 | East | New York | Crackers | Whole Wheat | 23 | 3.49 | 80.27 |
2020/4/13 | West | San Diego | Snacks | Potato Chips | 28 | 1.68 | 47.04 |
2020/4/16 | East | Boston | Bars | Carrot | 48 | 1.77 | 84.96 |
2020/4/19 | East | Boston | Snacks | Potato Chips | 134 | 1.68 | 225.12 |
2020/4/22 | West | Los Angeles | Bars | Carrot | 20 | 1.77 | 35.4 |
2020/4/25 | East | New York | Bars | Carrot | 53 | 1.77 | 93.81 |
2020/4/28 | East | New York | Snacks | Potato Chips | 64 | 1.68 | 107.52 |
2020/5/1 | West | San Diego | Cookies | Chocolate Chip | 63 | 1.87 | 117.81 |
2020/5/4 | East | Boston | Bars | Bran | 105 | 1.87 | 196.35 |
2020/5/7 | East | Boston | Cookies | Oatmeal Raisin | 138 | 2.84 | 391.92 |
相关推荐
- 在NAS实现直链访问_如何访问nas存储数据
-
平常在使用IPTV或者TVBOX时,经常自己会自定义一些源。如何直链的方式引用这些自定义的源呢?本人基于armbian和CasaOS来创作。使用标准的Web服务器(如Nginx或Apache...
- PHP开发者必备的Linux权限核心指南
-
本文旨在帮助PHP开发者彻底理解并解决在Linux服务器上部署应用时遇到的权限问题(如Permissiondenied)。核心在于理解“哪个用户(进程)在访问哪个文件(目录)”。一、核心...
- 【Linux高手必修课】吃透sed命令!文本手术刀让你秒变运维大神!
-
为什么说sed是Linux运维的"核武器"?想象你有10万个配置文件需要批量修改?传统方式要写10万行脚本?sed一个命令就能搞定!这正是运维工程师的"暴力美学"时...
- 「实战」docker-compose 编排 多个docker 组成一个集群并做负载
-
本文目标docker-compose,对springboot应用进行一个集群(2个docker,多个类似,只要在docker-compose.yml再加boot应用的服务即可)发布的过程架构...
- 企业安全访问网关:ZeroNews反向代理
-
“我们需要让外包团队访问测试环境,但不想让他们看到我们的财务系统。”“审计要求我们必须记录所有第三方对内部系统的访问,现在的VPN日志一团糟。”“每次有新员工入职或合作伙伴接入,IT部门都要花半天时间...
- 反向代理以及其使用场景_反向代理实现过程
-
一、反向代理概念反向代理(ReverseProxy)是一种服务器配置,它将客户端的请求转发给内部的另一台或多台服务器处理,然后将响应返回给客户端。与正向代理(ForwardProxy)不同,正向代...
- Nginx反向代理有多牛?一篇文章带你彻底搞懂!
-
你以为Nginx只是个简单的Web服务器?那可就大错特错了!这个看似普通的开源软件,实际上隐藏着惊人的能力。今天我们就来揭开它最强大的功能之一——反向代理的神秘面纱。反向代理到底是什么鬼?想象一下你...
- Nginx反向代理最全详解(原理+应用+案例)
-
Nginx反向代理在大型网站有非常广泛的使用,下面我就重点来详解Nginx反向代理@mikechen文章来源:mikechen.cc正向代理要理解清楚反向代理,首先:你需要搞懂什么是正向代理。正向代理...
- centos 生产环境安装 nginx,包含各种模块http3
-
企业级生产环境Nginx全模块构建的大部分功能,包括HTTP/2、HTTP/3、流媒体、SSL、缓存清理、负载均衡、DAV扩展、替换过滤、静态压缩等。下面我给出一个完整的生产环境安装流程(C...
- Nginx的负载均衡方式有哪些?_nginx负载均衡机制
-
1.轮询(默认)2.加权轮询3.ip_hash4.least_conn5.fair(最小响应时间)--第三方6.url_hash--第三方...
- Nginx百万并发优化:如何提升100倍性能!
-
关注△mikechen△,十余年BAT架构经验倾囊相授!大家好,我是mikechen。Nginx是大型架构的核心,下面我重点详解Nginx百万并发优化@mikechen文章来源:mikechen....
- 在 Red Hat Linux 上搭建高可用 Nginx + Keepalived 负载均衡集群
-
一、前言在现代生产环境中,负载均衡是确保系统高可用性和可扩展性的核心技术。Nginx作为轻量级高性能Web服务器,与Keepalived结合,可轻松实现高可用负载均衡集群(HA+LB...
- 云原生(十五) | Kubernetes 篇之深入了解 Pod
-
深入了解Pod一、什么是PodPod是一组(一个或多个)容器(docker容器)的集合(就像在豌豆荚中);这些容器共享存储、网络、以及怎样运行这些容器的声明。我们一般不直接创建Pod,而是...
- 云原生(十七) | Kubernetes 篇之深入了解 Deployment
-
深入了解Deployment一、什么是Deployment一个Deployment为Pods和ReplicaSets提供声明式的更新能力。你负责描述Deployment中的目标状...
- 深入理解令牌桶算法:实现分布式系统高效限流的秘籍
-
在高并发系统中,“限流”是保障服务稳定的核心手段——当请求量超过系统承载能力时,合理的限流策略能避免服务过载崩溃。令牌桶算法(TokenBucket)作为最经典的限流算法之一,既能控制请求的平...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (77)
- python封装 (57)
- python写入txt (66)
- python读取文件夹下所有文件 (59)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)