Skip to content

Instantly share code, notes, and snippets.

@peter88213
Created June 12, 2023 15:54
Show Gist options
  • Save peter88213/7fcb2f08e612f4a4b320be5d21b29db6 to your computer and use it in GitHub Desktop.
Save peter88213/7fcb2f08e612f4a4b320be5d21b29db6 to your computer and use it in GitHub Desktop.
Change the shades of table cells in a docx 'document.xml' component.
import xml.etree.ElementTree as ET
ns = dict(
ve="http://schemas.openxmlformats.org/markup-compatibility/2006",
o="urn:schemas-microsoft-com:office:office",
r="http://schemas.openxmlformats.org/officeDocument/2006/relationships",
m="http://schemas.openxmlformats.org/officeDocument/2006/math",
v="urn:schemas-microsoft-com:vml",
wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",
w10="urn:schemas-microsoft-com:office:word",
w="http://schemas.openxmlformats.org/wordprocessingml/2006/change_cell_shade",
wne="http://schemas.microsoft.com/office/word/2006/wordml",
)
def change_cell_shade(documentPath, oldColor, newColor):
"""Change the shades of table cells in a docx 'document.xml' component.
Precondidtion:
'document.xml' is extracted from the .docx file.
Postcondition:
Cell shades have been changed from oldColor to newColor.
Now you can replace 'document.xml' in your .docx file.
"""
for namespace in ns:
ET.register_namespace(namespace, ns[namespace])
tree = ET.parse(documentPath)
for xmlElement in tree.iter():
xmlCell = xmlElement.find('w:tcPr', ns)
if xmlCell is not None:
xmlShade = xmlCell.find('w:shd', ns)
if xmlShade is not None:
if xmlShade.attrib.get(f'{{{ns["w"]}}}fill', '') == oldColor:
xmlShade.attrib[f'{{{ns["w"]}}}fill'] = newColor
tree.write(documentPath, xml_declaration=True, encoding='utf-8')
if __name__ == '__main__':
documentPath = 'document.xml'
oldColor = 'FFC000'
newColor = '00C0FF'
change_cell_shade(documentPath, oldColor, newColor)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment