现在你是一个资深的python程序员,我将提供一段断码给你,帮我检查和优化代码:‘’‘{import openpyxl from openpyxl.styles import Font wb = openpyxl.load_workbook('百优评审简况表-兰敏(文物组).xlsx') ws = wb['模板1'] font_1 = Font(name='黑体',size=14) font = Font(name='仿宋_GB2312',size=13) font_2 = Font(name='仿宋_GB2312',size=12) font_3 = Font(name='Times New Roman',size=13) for i in range(3,11): for col in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']: if col == 'A' and (i in [3,4,5,6]): for row in range(i,ws.max_row + 1,10): cell = f"{col}{row}" ws[cell].font = font_1 if col == 'B' and (i in [3,4]): for row in range(i,ws.max_row + 1,10): cell = f"{col}{row}" ws[cell].font = font if col == 'B' and (i in [5,6,7,8,9]): for row in range(i,ws.max_row + 1,10): cell = f"{col}{row}" ws[cell].font = font_1 if col == 'C' and i == 5: for row in range(i,ws.max_row + 1,10): cell = f"{col}{row}" ws[cell].font = font if col == 'D' and (i in [6, 7, 8, 9]): for row in range(i, ws.max_row + 1, 10): cell = f"{col}{row}" ws[cell].font = font_2 if col == 'E' and i == 5: for row in range(i,ws.max_row + 1,10): cell = f"{col}{row}" ws[cell].font = font_1 if col == 'F' and i == 5: for row in range(i,ws.max_row + 1,10): cell = f"{col}{row}" ws[cell].font = font if col == 'G' and (i in [4,5]): for row in range(i,ws.max_row + 1,10): cell = f"{col}{row}" ws[cell].font = font_1 if col == 'H' and i == 3: for row in range(i,ws.max_row + 1,10): cell = f"{col}{row}" ws[cell].font = font_3 if col == 'H' and i == 4: for row in range(i,ws.max_row + 1,10): cell = f"{col}{row}" ws[cell].font = font wb.save('test.xlsx')}’‘’
时间: 2024-03-02 15:51:54 浏览: 133
根据您提供的代码,我发现其中存在冗余的if语句和重复的代码,可以进行优化。下面是优化后的代码:
```
import openpyxl
from openpyxl.styles import Font
wb = openpyxl.load_workbook('百优评审简况表-兰敏(文物组).xlsx')
ws = wb['模板1']
font_1 = Font(name='黑体',size=14)
font_2 = Font(name='仿宋_GB2312',size=12)
font_3 = Font(name='Times New Roman',size=13)
font_4 = Font(name='仿宋_GB2312',size=13)
for i in range(3, 11):
for col in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']:
for row in range(i, ws.max_row + 1, 10):
cell = f"{col}{row}"
if col == 'A' and i in [3, 4, 5, 6]:
ws[cell].font = font_1
elif col == 'B' and i in [3, 4, 5, 6, 7, 8, 9]:
ws[cell].font = font_1
if i in [3, 4]:
ws[cell].font = font_2
elif col == 'C' and i == 5:
ws[cell].font = font_2
elif col == 'D' and i in [6, 7, 8, 9]:
ws[cell].font = font_2
elif col == 'E' and i == 5:
ws[cell].font = font_1
elif col == 'F' and i == 5:
ws[cell].font = font_4
elif col == 'G' and i in [4, 5]:
ws[cell].font = font_1
elif col == 'H' and i == 3:
ws[cell].font = font_3
elif col == 'H' and i == 4:
ws[cell].font = font_4
wb.save('test.xlsx')
```
在优化后的代码中,我们使用了else if语句来替换多个if语句,使代码更加简洁易读。同时,我们使用了一个新的字体font_4,用于替换原来的font。
阅读全文