如何在 python-docx 中获取单元格背景颜色?

How to get cell background color in python-docx?

我正在尝试使用 python-docx 从 MS Word table 读取数据。 有一种方法可以设置 table 单元格的背景颜色:

tcPr = cell._tc.get_or_add_tcPr()
shd = OxmlElement("w:shd")
shd.set(qn("w:fill"), rgb2hex(*color))
tcPr.append(shd)

我的任务是相反的,我需要得到现有的颜色。我不擅长xml,我试过这个:

cell = table.cell(row, col)
tcPr = cell._tc.get_or_add_tcPr().get(qn('w:shd'))

如何 returns 我 None 每个读取的单元格,无论其颜色如何。

正如scanny提议的那样,我使用了解析cell._tc.xml:

pattern = re.compile('w:fill=\"(\S*)\"')
match = pattern.search(cell._tc.xml)
result = match.group(1)

如果有关于颜色的数据,它 returns "auto" 或可以转换为 RGB 的背景颜色的十六进制代码。

正如scanny所说,你首先要确定你要找的element/property

但是要读取该元素的值,您应该使用 find 方法。

例如:

cell._tc.get_or_add_tcPr().get(qn('w:shd')) #Returns None
cell._tc.get_or_add_tcPr().find(qn('w:shd')) #Returns <Element {http://schemas.openxmlformats.org/wordprocessingml/2006/main}shd at ...>