Python:openpyxl如何读取单元格字体颜色 [英] Python: openpyxl how to read a cell font color

查看:1703
本文介绍了Python:openpyxl如何读取单元格字体颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试打印some_cell.font.color.rgb并获得了各种结果.

I have tried to print some_cell.font.color.rgb and got various results.

对于某些人,我得到了想要的东西(例如"FF000000"),但是对于其他人,它却给了我Value must be type 'basetring'.我认为后者是因为我实际上尚未为这些单元格定义字体颜色.

For some I got what I want (like "FF000000"), but for others it gives me Value must be type 'basetring'. I assume that the latter is because I haven't actually defined the font color for these cells.

我正在使用openpyxl 2.2.2

I'm using openpyxl 2.2.2

推荐答案

我认为这是openpyxl中的错误,我认为您应该报告它此处.

I think this is a bug in openpyxl and I think you should report it here.

调试以下代码(当然使用 trepan3k ):

Debugging the following code (with trepan3k of course):

from openpyxl import Workbook
wb = Workbook()
ws = wb.active
c = ws['A4']  # cell gets created here
print(ws['A4'].font.color)

我得到:

Color(rgb=Value must be type 'str', indexed=Value must be type 'int', auto=Value must be type 'bool', theme=1, tint=0.0, type='theme')

,这来自文件openpyxl/descriptors/base.py Typed()类的 _repr _().尚未初始化值时会给出此消息.请注意,还没有设置索引"和自动".

and this is coming from _repr_() of class Typed() in file openpyxl/descriptors/base.py. This message is given when a value hasn't been initialized. Notice that "indexed" and "auto" also haven't been set.

但是这些大概应该在执行ws['a4']的访问代码时已设置.

But these presumably should have been set when the code for the access of ws['a4'] was performed.

注意:消息中的'str'而不是'basestring'略有不同可能是由于我使用的是Python 3或更小版本的openpyxl 2.2.3

如果我应该在示例中添加其他代码,则至少

And if there's some other additional code should that I should have added in my example, then at least https://openpyxl.readthedocs.org/en/latest/index.html should indicate that.

另请参见 openpyxl单元格样式无法正确报告一位开发人员似乎用太多的话说了同样的话.

See also openpyxl cell style not reporting correctly where one of the developers seems to say the same thing in so many words.

修改:

可能还需要注意其他几件事.首先,您可以设置一个值,然后读取它,例如,您可以执行以下操作:

A couple of other things may be of interest to note. First, you can set a value and then read it, for example you can do this:

c.font.color.rgb = "FF000000"

第二,如果您在布尔值中测试c.font.color.rgb,它将看起来像已设置了值.那是

Second, if you test c.font.color.rgb in a boolean it will look like a value has been set. That is

if c.font.color: print("yes")

将显示是".

这篇关于Python:openpyxl如何读取单元格字体颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆