在做一个小工具,其中有个步骤需要获取单元格颜色,但是我的EXCEL单元格有的是填充色,有的是渐变色。我使用如下代码碰到问题:
import openpyxl
filename="教员排班表.xlsx"#读取excel
workbook=openpyxl.load_workbook(filename)
worksheet=workbook["2021.11"]#读取Sheet
rows = 33
for i in range(1,rows):
ce=worksheet.cell(row=i+1,column=5)
fill = ce.fill
print(fill.fgColor.rgb)
结果是:
00000000
FFBEB1AA
FF33CCFF
Traceback (most recent call last):
File "d:\Private\Sync\我的坚果云\python\testexcel copy 2.py", line 15, in <module>
print(fill.fgColor.rgb)
File "C:\Users\Jshi\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\styles\proxy.py", line 24, in __getattr__
return getattr(self.__target, attr)
AttributeError: 'GradientFill' object has no attribute 'fgColor'
也就是说,在第五列第四行碰到了一个渐变色的单元格后报错了,请问怎么处理呢?
可以使用try/except异常处理,示例:
try:
print(fill.fgColor.rgb)
except:
print(fill.stop[0].color,fill.stop[1].color)
尝试异常补获