使用openpyxl库修改xlsx(根据某列的值对相应单元格进行颜色填充,题库类excel文档高亮答案项)


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,保存,非常重要。

代码注释部分为单选的代码,未注释的部分为多选的代码。

效果如下图

 

 

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值