[892] Change the background color of a table in a Word document

发布时间 2023-09-27 13:20:18作者: McDelfino

ref: python-docx Changing Table Cell Background Color.


To change the background color of a table in a Word document using Python, you can use the python-docx library, which allows you to create and modify Word documents programmatically. Here's how to change the background color of a table in a Word document:

Install the python-docx Library (if not already installed):

You can install the python-docx library using pip:

pip install python-docx

Import the docx Module:

In your Python script, import the docx module:

import docx

Open the Word Document:

Open the Word document that contains the table you want to modify. You can open an existing document or create a new one:

# Open an existing Word document
doc = docx.Document('path/to/your/document.docx')

# Create a new Word document
doc = docx.Document()

Access the Table and Modify Its Style:

To change the background color of a specific table in the document, you'll need to access that table and modify its style.

# Assuming you want to modify the first table in the document
table = doc.tables[0]

# Only change the sencond row's background color
row_1 = table.rows[1]

# Change all cells' background color (white) of the second row
for cell in row_1.cells:
    # get cells XML element
    cell_xml_element = cell._tc
    # retreieve the table cell properties
    table_cell_properties = cell_xml_element.get_or_add_tcPr()
    # create shading object
    shade_obj = OxmlElement('w:shd')
    # set the shading object
    shade_obj.set(qn('w:fill'), "ffffff")
    # append the properties to the table calee properties
    table_cell_properties.append(shade_obj) 

doc.save(docx_document)