如何在python-docx中获取单元格背景颜色? [英] How to get cell background color in python-docx?
本文介绍了如何在python-docx中获取单元格背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 python-docx 从 MS Word 表中读取数据.有一种方法可以设置表格单元格的背景颜色:
I'm trying to read data from MS Word table using python-docx. There is a way to set background color of a table cell:
tcPr = cell._tc.get_or_add_tcPr()
shd = OxmlElement("w:shd")
shd.set(qn("w:fill"), rgb2hex(*color))
tcPr.append(shd)
我的任务相反,我需要获取现有的颜色.我不擅长 xml,我试过这个:
My task is contrary, I need to get the existing color. I'm not skilled in xml and I tried this:
cell = table.cell(row, col)
tcPr = cell._tc.get_or_add_tcPr().get(qn('w:shd'))
它如何为每个读取的单元格返回无,无论其颜色如何.
How ever it returns me None for each read cell regardless of its color.
推荐答案
作为 scanny 提出的,我使用了解析单元格._tc.xml:
As scanny proposed, I used parsing cell._tc.xml:
pattern = re.compile('w:fill=\"(\S*)\"')
match = pattern.search(cell._tc.xml)
result = match.group(1)
如果有颜色数据,它返回自动"或背景颜色的十六进制代码,可以转换为 RGB.
If there is data on color it returns either "auto" or hex code of background color which can be converted to RGB.
这篇关于如何在python-docx中获取单元格背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文