python批量快速合并excel文件

您所在的位置:网站首页 python读取多个excel文件 python批量快速合并excel文件

python批量快速合并excel文件

#python批量快速合并excel文件| 来源: 网络整理| 查看: 265

python批量快速合并excel文件 原创

喵来个鱼 2019-08-03 09:14:24 博主文章分类:python ©著作权

文章标签 python excel xlrd xlsxwriter 批量 文章分类 Linux 系统/运维

©著作权归作者所有:来自51CTO博客作者喵来个鱼的原创作品,请联系作者获取转载授权,否则将追究法律责任python批量快速合并excel文件https://blog.51cto.com/m51cto/2426135 简介

如果有很多excel文件需要合并到一个Excel文件中,使用复制粘贴来操作是非常痛苦,这时可以使用Python来批量自动操作。

把需要合并的Excel文件放到同一文件夹下。

安装需要的库

python环境Python3

pip3 install xlrd pip3 install xlsxwriter 代码 #!/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合并完成")

运行脚本:

python3 megerexcel.py

python批量快速合并excel文件

python批量快速合并excel文件

打赏 收藏 评论 分享 微博 QQ 微信 举报

上一篇:docker快速搭建分布式爬虫pyspider

下一篇:win7通过wsus升级到win10总结



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3