简体   繁体   中英

Word table cell background color using python-docx

I have a simple word document with a single table containing one row and two columns (in other words, two cells). The background color of the first cell is red, and the other is black. I want to change both to white using python-docx.

I've tried several approaches but the one that seems most promising is below. It modifies the underlying xml.

import docx
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml

# Set a cell background (shading) color to RGB D9D9D9. 
shading_elm = parse_xml(r'<w:shd {} w:fill="FFFFFF"/>'.format(nsdecls('w')))

doc = docx.Document('assets/tabletest.docx')
table = doc.tables[0]

cell = table.cell(0,0)
testchild = cell._tc.getchildren()[0]
testchild.append(shading_elm)

doc.save('assets/tabletest2.docx')

The code above modifies the first cell to be white and leaves the second cell as black. I try to modify the second cell by adding the code below before the doc.save :

cell2 = table.cell(0,1)
testchild2 = cell2._tc.getchildren()[0]
testchild2.append(shading_elm)

The issue is that now, the first cell is still red and the second cell is now white. It seems to only be modifying the last cell.

I am definitely missing something but I am not an xml expert. Does anyone have ideas?

Best bet is to explore the actual XML to see what you're trying to modify. The OpenXML Schema is quite complicated and Word does all kinds of things in the course of editing that you might not expect. _tc.getchildren()[0] just gets whatever is first in line as a child and I'm not sure that it's unconditionally a tcPr element ready to accept a <w:shd> element. Also, if there's already a w:shd element there, you want to update it, rather than add a new one.

I recommend using opc-diag to browse the document.xml part of the .docx package you're working with. It will be easier to find the bit you're after if you remove other content from the document.

If you'll post the XML you find there I can help you work out what to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM