关于Excel表操作-合并文件操作

最近有点忙有点烦,天天忙于数据治理,说是数据治理,整天就是忙于整理和下发各种表格,从开始下发到各地区的表格合并进来,再到入库,再到比对,再到分离下发,再到按字段拆分,从xlrd,lxlwr,openpyxl,pandas,再到cx_Oracle,再到fuzzywuzzy,gensim等等,从最初的流水版本进化到封装成类,挺繁琐的,不过也挺好玩的。

f665fab3cd715ce4e1119139dc38c2ec.png

整个文件的资源目录结构如下

bc51f35b81cdef091877b4ce45f20197.png

要做的事情就是把各子文件夹下文件名为《文件类型一》、《文件类型二》、《文件类型三》的全合并成一个个大文件,sheet名都是Sheet0,还是有章可循的。

import os
import openpyxl
asepath = r'C:\Users\baoqi\Documents\'
sheetname='Sheet0'
destfilename=r'C:\Users\baoqi\Documents\海南\文件类型一.lsx'
keyword='文件类型一'
# 获取当前文件夹下的各单位文件夹
allpath = os.listdir(basepath)
data = []
for curpath in allpath:
# 拼接路径及文件
fullpath = basepath + '\\'+curpath
if os.path.isfile(fullpath):
continue
allfiles=os.listdir(fullpath)

# 获取各单位文件夹下的文件
for curfile in allfiles:
curpathfile=fullpath+'\\'+curfile
if not os.path.isfile(curpathfile) or '~' in curfile:
continue
if keyword in curfile:
print('读取文件 ',curpathfile)
lsdatalist=[]
# 打开文件,打开指定sheet
wb = openpyxl.load_workbook(curpathfile)
sh = wb[sheetname]
# 获取sheet数据
rows = list(sh.rows)
# 遍历读取行信息,并附加补充列
for row in rows[4:]:

case = []

# 追加了一些区识字段                case.append(keyword)

case.append(curpath)
for r in row:
case.append(r.value)
data.append(case)
wb.close()

print('{} 共读取{}行'.format(keyword,len(data)))

wb = openpyxl.Workbook()
sh = wb.active
sh.title = sheetname
for ss in data:
sh.append(ss)
wb.save(destfilename)
print( "写入{}文件成功!".format(destfilename))

代码还是有很多简化和优化空间的。

最后,谢谢关注,谢谢支持!

05f54c0490173ba47825e3b41f5f061d.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

python与大数据分析

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值