时间急大概先写下概要,后面再补详情
主要用于解决把一个文件夹中所有excel表中的文件名取出来,在新的excel表中汇总并保存
记得先安装python3和pip3,对应下载xlwt和sys等
# coding=utf-8
import os
import xlwt #操作excel模块
import sys
f = xlwt.Workbook(encoding='utf-8', style_compression=0) #新建一个excel
sheet = f.add_sheet('sheet1') #新建一个sheet
pathDir = "C:/Users/Administrator/Desktop/test" #文件路径,用来获取当前文件夹内所有文件目录
allfilenames = os.listdir(pathDir) #将文件名列出并存储在allfilenames里面
i = 0 #将文件列表写入test.xls
for s in allfilenames:
sheet.write(i, 0, '发货单') #参数i,0,s分别代表行,列,写入值
t = s.replace(".xlsx", "").replace(".xls", "")
sheet.write(i, 1, t) #参数i,0,s分别代表行,列,写入值
i = i+1
print(i) #显示文件名数量
f.save('C:/Users/Administrator/Desktop/2020-11-05-filenames-excel.xls') #保存的文件路径
最后保存出来的结果如下:
接着根据文件夹中所有excel表,取每个表中对应的各个想要的值,当然这要求所有execl表中格式都一样,即每个值所在的单元格是一致的
# coding=utf-8
import os
import xlwt #操作excel模块
import sys
import xlrd #操作excel模块
from datetime import datetime
from xlrd import xldate_as_tuple
f = xlwt.Workbook(encoding='utf-8', style_compression=0) #新建一个excel
sheet = f.add_sheet('sheet1') #新建一个sheet
pathDir = "C:/Users/Administrator/Desktop/tttt" #文件路径,用来获取当前文件夹内所有文件目录
allfilenames = os.listdir(pathDir) #将文件名列出并存储在allfilenames里面
list_name=[] # 所有路径数组
# 执行把文件夹下所有路径保存到本地用于后面for循环打开
def listdir(path, list_name): # 传入存储的list
for file in os.listdir(path):
file_path = os.path.join(path, file)
if os.path.isdir(file_path):
listdir(file_path, list_name)
else:
list_name.append(file_path)
listdir(pathDir, list_name)
print(list_name) # 打印所有路径数组
data = [] # 应该存入的所有excel列表数据
for i in list_name:
wb = xlrd.open_workbook(i) # 先打开第一个文件1.xlsx
time = wb.sheets()[0].cell(7,5).value
date = datetime(*xldate_as_tuple(time, 0))
time = date.strftime('%Y/%m/%d')
rows = {
'time': time, # 日期
'customer': wb.sheets()[0].cell(16,2).value, # 客户
'code': wb.sheets()[0].cell(8,1).value, # 编号
'name': wb.sheets()[0].cell(7,1).value, # 销售名字
}
print(rows) # 打印该列表
data.append(rows) # 把其数据放入 data[]列表中
print(data) # 打印excel列表数据该列表
sheet.write(0, 1, '日期')
sheet.write(0, 2, '客户')
sheet.write(0, 3, '编号')
sheet.write(0, 4, '销售')
sheet.write(0, 5, '发货单')
# 将先前所有列表数据逐步放入对应的单元格中
d = 1
for item in data:
print(item) # 打印该列表
sheet.write(d, 1, item['time'])
sheet.write(d, 2, item['customer'])
sheet.write(d, 3, item['code'])
sheet.write(d, 4, item['name'])
d = d + 1
i = 1 #将文件列表写入test.xls
for s in allfilenames:
sheet.write(i, 0, '信息')
t = s.replace(".xlsx", "").replace(".xls", "") # 截取后缀名并替换掉
sheet.write(i, 5, t) #参数i,0,t分别代表行,列,写入值
i = i+1
print(i) # 打印文件总数量
f.save('C:/Users/Administrator/Desktop/test.xls') #保存的文件路径
最后保存出来的结果如下: