百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

如何使用 Python 将多个 excel 文件合并为一个文件?

off999 2024-12-17 15:42 13 浏览 0 评论

通常,我们正在处理 Excel 文件,我们肯定遇到过需要将多个 Excel 文件合并为一个文件的情况。传统方法一直是在 excel 中使用 VBA 代码,它可以完成这项工作,但是不太容易理解。另一种方法是手动将长Excel文件复制到一个文件中,这不仅耗时,麻烦,而且容易出错。

使用 python中的Pandas 模块即可轻松快速地完成此任务。如果未安装Pandas模块在终端中使用以下命令:

Bash
pip install pandas

1、导入库

Bash
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


相关推荐

工程师必备!DeepSeek自动化运维全攻略

每天省出3小时,故障自修复+智能监控实战指南导语“总在深夜被报警短信吵醒?教你搭建智能运维体系,让DeepSeek自己管自己!”正文技能1:自动化故障诊断配置智能诊断规则:yaml复制alert_ru...

Spug - 轻量级自动化运维平台(自动化运维平台 devops)

对于中小型企业而言,进行主机和应用的管理是比较麻烦的,应用部署往往需要直接连接服务器,再进行手动的环境配置、代码拉取、应用构建和部署发布等工作,容易出错,且耗时费力。一个好的自动化运维平台,往往能大大...

轻量级无 Agent 的一个好用的“小麻雀”自动化运维平台工具!-Spug

对于中小型企业而言,进行主机和应用的管理是比较麻烦的,应用部署往往需要直接连接服务器,再进行手动的环境配置、代码拉取、应用构建和部署发布等工作,容易出错,且耗时费力。一个好的自动化运维平台,往往能大大...

运维自动化之实用python代码汇总(python自动化运维常用模块)

本文总结了运维工作中经常用到的一些实用代码块,方便在需要的时候直接搬过来使用即可1.执行系统命令,获取返回结果fromsubprocessimportPopen,PIPE,STDOUTcp...

从代码小白到自动化大师:Python 编程实战

昨天我聊了一下关于线性代数、概率统计、微积分核心概念的学习,也花了一些时间恢复一下大学时候学这些的记忆,确实来说数学很有趣也很考验人,兴趣是最好的老师对吧,既然对AI感兴趣,总要认真的学一学,接下来我...

锐捷:基于Python TextFSM模块的网络设备自动化运维方法

网络设备自动化运维,首先要实现网络设备与自动化运维平台对接,即通过代码实现登录网络设备并获取信息。邮政业科技创新战略联盟单位锐捷自主研发的数据中心交换机产品已全面支持NETCONF协议,可适用于和SD...

基于Python+vue的自动化运维、完全开源的云管理平台

真正的大师,永远都怀着一颗学徒的心!一、项目简介今天说的这个软件是一款基于Python+vue的自动化运维、完全开源的云管理平台。二、实现功能基于RBAC权限系统录像回放DNS管理配置中心强大的作业调...

编程与数学:在Python里怎么用turtle库函数填色?

这里只给出一个示例,一个最简单的示例。看懂这个示例,你就能在自己的代码里需要填色的地方填色。首先,与前面发的Python绘画程序一样,先要装入turtle库。然后在代码中,下面需要填色时,先写一个填色...

Python UV 环境下的 PyKDL 运动学库安装

视频讲解:PythonUV环境下的PyKDL运动学库安装_哔哩哔哩_bilibilimujoco-learning这个仓库,改成uv管理环境依赖后,原来的一些包有些缺失,比如之前安装的PyKD...

python最新版3.11正式发布,有哪些新特色?(3/5)

异步任务的语法更完美python编程语言对异步编程的支持一直在改进,比如python2.0版开始就增加了生成器(generator),在3.4版开始增加了asyncio库,随后在3.5版中...

清华北大都在用!Python王者归来(全彩版)

纸上得来终觉浅,绝知此事要躬行。今天给大家带来一份由清华大学出版的《python王者归来》。在当下全民互联网,大数据的时代,Python已然成为了学习大数据、人工智能时代的首选编程语言,Python...

第六章:Python模块与包(python模块与包与类的关系区别)

6.1模块基础6.1.1理论知识模块是一个包含Python定义和语句的文件,其扩展名为.py。模块可以将代码组织成逻辑单元,提高代码的可维护性和复用性。通过将相关的函数、类和变量放在同一个模块中...

语言教育项目实战之一:Ubuntu下安装Python环境

如下项目,运行在#ubuntu#上,使用#pytho#,从最初环境开始,逐渐深入。此项目以语言学习为主要目的,实现听写、跟读、对话的服务,面向中小学生、大学生、涉外交流人员等。计划通过pyenv管...

openai-python v1.79.0重磅发布!全新Evals API升级,音频转录终极

2025年5月17日,OpenAI官方在GitHub上发布了openai-python库的最新版本——v1.79.0。本次版本重点围绕Evals评估API进行了多项功能完善,同时修复了音频转录接口的重...

你真的用对了吗?7个常被误用的Python内置函数及最佳实践

你是否曾经在使用多年的工具中突然发现一个新功能,然后感叹:“我怎么一直没发现这个?”没错,今天我们就来体验一把“Python函数版”的这种乐趣。这些函数很可能已经是你日常代码的一部分,但我敢打赌,你并...

取消回复欢迎 发表评论: