import openpyxl
from openpyxl.styles import PatternFill
book = openpyxl.load_workbook(r'xxx.xlsx')
ws=book.worksheets[1]
# sheet1=ws.worksheets[0]
print(ws.title)
rows=ws.max_row
# for row in range(1,rows+1):
# print(row)
# if ws.cell(row,7).value=='A':
# print('a found')
# ws.cell(row,3).fill= PatternFill("solid", fgColor="00FF00")
# print('color set!')
# if ws.cell(row,7).value=='B':
# print('b found')
# ws.cell(row,4).fill= PatternFill("solid", fgColor="00FF00")
# print('color set!')
# if ws.cell(row,7).value=='C':
# print('c found')
# ws.cell(row,5).fill= PatternFill("solid", fgColor="00FF00")
# print('color set!')
# if ws.cell(row,7).value=='D':
# print('d found')
# ws.cell(row,6).fill= PatternFill("solid", fgColor="00FF00")
# print('color set!')
for row in range(1,rows+1):
print(row)
if 'A' in ws.cell(row,7).value:
print('a found')
ws.cell(row,3).fill= PatternFill("solid", fgColor="00FF00")
print('color set!')
if 'B' in ws.cell(row,7).value:
print('b found')
ws.cell(row,4).fill= PatternFill("solid", fgColor="00FF00")
print('color set!')
if 'C' in ws.cell(row,7).value:
print('c found')
ws.cell(row,5).fill= PatternFill("solid", fgColor="00FF00")
print('color set!')
if 'D' in ws.cell(row,7).value:
print('d found')
ws.cell(row,6).fill= PatternFill("solid", fgColor="00FF00")
print('color set!')
book.save('xxx.xlsx')
print('done')
代码比较丑陋
务必确保要操作的excel表格处于关闭状态,否则程序无法操作。
1,加载已有的xlsx文件,使用的r+字符串,r"" 的作用是去除转义字符,避免无法直接使用从windows复制的文件路径,例如\windows,会被认为是\w
2,选择需要修改的工作表
3,遍历答案列,发现'A'(单选)或'A' in value(多选),就把对应的答案项进行颜色填充
4,保存,非常重要。
代码注释部分为单选的代码,未注释的部分为多选的代码。
效果如下图