如果有很多excel文件需要合并到一个Excel文件中,使用复制粘贴来操作是非常痛苦,这时可以使用Python来批量自动操作。
把需要合并的Excel文件放到同一文件夹下。
安装需要的库
python环境Python3
复制代码
1
2
3pip3 install xlrd pip3 install xlsxwriter
代码
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: Aiker Zhao # @Date : 2019/5/4 9:34 AM # @File : megerexcel.py # @Desc : import xlrd import xlsxwriter import os path = "/Users/Aiker/Documents/xzexcel/1-6/" def get_allxls(): # 获取excel文件列表 all_xls = [] for f in os.listdir(path): f_name = path + f all_xls.append(f_name) return all_xls def open_xls(file): # 打开一个excel fh = xlrd.open_workbook(file) return fh def getsheet(fh): # 获取excel表中的所有sheet return fh.sheets() def getnrows(fh, sheet): # 获取sheet表中的行数 table = fh.sheets()[sheet] return table.nrows def getFilect(file, shnum): # 读取文件内容并返回内容 fh = open_xls(file) table = fh.sheets()[shnum] num = table.nrows for row in range(num): rdata = table.row_values(row) datavalue.append(rdata) return datavalue def getshnum(fh): # 获取sheet表的个数 x = 0 sh = getsheet(fh) for sheet in sh: x += 1 return x if __name__ == '__main__': allxls = get_allxls() # 定义要合并的excel文件列表 datavalue = [] for fl in allxls: # 存储所有读取的结果 fh = open_xls(fl) x = getshnum(fh) for shnum in range(x): print("正在读取文件:" + str(fl) + "的第" + str(shnum) + "个sheet表的内容...") rvalue = getFilect(fl, shnum) endfile = "/Users/Aiker/Documents/xzexcel/行政工作统计19-6.xls" # 合并后的文件 wb1 = xlsxwriter.Workbook(endfile) ws = wb1.add_worksheet() for a in range(len(rvalue)): for b in range(len(rvalue[a])): c = rvalue[a][b] ws.write(a, b, c) wb1.close() print("excel合并完成") 在学习过程中有什么不懂得可以加我的 python学习交流扣扣qun,784758214 群里有不错的学习视频教程、开发工具与电子书籍。 与你分享python企业当下人才需求及怎么从零基础学习好python,和学习什么内容
运行脚本:
复制代码
1
2
3python3 megerexcel.py
最后
以上就是迷你鞋子最近收集整理的关于python批量快速合并excel文件的全部内容,更多相关python批量快速合并excel文件内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复