How to get cell background color in python-docx?

…衆ロ難τιáo~ 提交于 2019-12-24 21:53:57

问题


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)

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.


回答1:


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)

If there is data on color it returns either "auto" or hex code of background color which can be converted to RGB.



来源:https://stackoverflow.com/questions/58324814/how-to-get-cell-background-color-in-python-docx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!