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

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

ztj100 2025-02-18 14:24 9 浏览 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


相关推荐

告别手动操作:一键多工作表合并的实用方法

通常情况下,我们需要将同一工作簿内不同工作表中的数据进行合并处理。如何快速有效地完成这些数据的整合呢?这主要取决于需要合并的源数据的结构。...

【MySQL技术专题】「优化技术系列」常用SQL的优化方案和技术思路

概述前面我们介绍了MySQL中怎么样通过索引来优化查询。日常开发中,除了使用查询外,我们还会使用一些其他的常用SQL,比如INSERT、GROUPBY等。对于这些SQL语句,我们该怎么样进行优化呢...

9.7寸视网膜屏原道M9i双系统安装教程

泡泡网平板电脑频道4月17日原道M9i采用Win8安卓双系统,对于喜欢折腾的朋友来说,刷机成了一件难事,那么原道M9i如何刷机呢?下面通过详细地图文,介绍原道M9i的刷机操作过程,在刷机的过程中,要...

如何做好分布式任务调度——Scheduler 的一些探索

作者:张宇轩,章逸,曾丹初识Scheduler找准定位:分布式任务调度平台...

mysqldump备份操作大全及相关参数详解

mysqldump简介mysqldump是用于转储MySQL数据库的实用程序,通常我们用来迁移和备份数据库;它自带的功能参数非常多,文中列举出几乎所有常用的导出操作方法,在文章末尾将所有的参数详细说明...

大厂面试冲刺,Java“实战”问题三连,你碰到了哪个?

推荐学习...

亿级分库分表,如何丝滑扩容、如何双写灰度

以下是基于亿级分库分表丝滑扩容与双写灰度设计方案,结合架构图与核心流程说明:一、总体设计目标...

MYSQL表设计规范(mysql表设计原则)

日常工作总结,不是通用规范一、表设计库名、表名、字段名必须使用小写字母,“_”分割。...

怎么解决MySQL中的Duplicate entry错误?

在使用MySQL数据库时,我们经常会遇到Duplicateentry错误,这是由于插入或更新数据时出现了重复的唯一键值。这种错误可能会导致数据的不一致性和完整性问题。为了解决这个问题,我们可以采取以...

高并发下如何防重?(高并发如何防止重复)

前言最近测试给我提了一个bug,说我之前提供的一个批量复制商品的接口,产生了重复的商品数据。...

性能压测数据告诉你MySQL和MariaDB该怎么选

1.压测环境为了尽可能的客观公正,本次选择同一物理机上的两台虚拟机,一台用作数据库服务器,一台用作运行压测工具mysqlslap,操作系统均为UbuntuServer22.04LTS。...

屠龙之技 --sql注入 不值得浪费超过十天 实战中sqlmap--lv 3通杀全国

MySQL小结发表于2020-09-21分类于知识整理阅读次数:本文字数:67k阅读时长≈1:01...

破防了,谁懂啊家人们:记一次 mysql 问题排查

作者:温粥一、前言谁懂啊家人们,作为一名java开发,原来以为mysql这东西,写写CRUD,不是有手就行吗;你说DDL啊,不就是设计个表结构,搞几个索引吗。...

SpringBoot系列Mybatis之批量插入的几种姿势

...

MySQL 之 Performance Schema(mysql安装及配置超详细教程)

MySQL之PerformanceSchema介绍PerformanceSchema提供了在数据库运行时实时检查MySQL服务器的内部执行情况的方法,通过监视MySQL服务器的事件来实现监视内...

取消回复欢迎 发表评论: