工作中遇到需要将多个excel表的文件名改成其在汇总表中对应的名称并标上序号。工作文件不能上传,把代码发出来供大家指正。
import os
from openpyxl import load_workbook
dict1 = {}
wb1 = load_workbook('C:\\Users\\xxxx\\Desktop\\test\\2021年项目支出绩效目标汇总表.xlsx')
wa1=wb1.active
for row in wa1.rows:
for cell in row:
if cell.column == 1:
numb = cell.value
if cell.column == 2:
div_name = cell.value
if cell.column == 3:
pro_name = cell.value
if cell.column == 5:
total = cell.value
dict1[pro_name] = [numb,div_name,total]
path = input('请输入文件夹路径,注意路径里的反斜杠写两遍:')
filenames = os.listdir(path)
for filename in filenames:
if filename[-1] == 'x':
path1 = path+'\\'+filename
wb = load_workbook(path1)
ws = wb.active
maxcol = ws.max_column
for row in ws.rows:
for cell in row:
if cell.value == '预算单位':
for i in range(1, maxcol):
if ws.cell(row=cell.row, column=i).value != None and ws.cell(row=cell.row, column=i).value != '预算单位':
dwmc = ws.cell(row=cell.row, column=i).value
if cell.value == '项目名称':
for j in range(1, maxcol):
if ws.cell(row=cell.row, column=j).value != None and ws.cell(row=cell.row, column=j).value != '项目名称':
xmmc = ws.cell(row=cell.row, column=j).value
for key in dict1.keys():
if xmmc == key :
try:
title = str(dict1[key][0])+'、'+dict1[key][1] +'-'+key+str(dict1[key][2])+'.xlsx'
print(title+'转换成功')
wb.save('C:\\Users\\lypzm\\Desktop\\test\\cs\\'+title)
except TypeError:
print(filename+'格式错误')
|