Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can modify the background and text color of a table cell using python-docx by doing the following:

  1. First, you need to import the necessary libraries:

    from docx import Document
    from docx.shared import RGBColor
    from docx.enum.table import WD_TABLE_ALIGNMENT
    from docx.enum.text import WD_COLOR_INDEX
    
  2. Next, you need to open the document that you want to modify:

    document = Document(path_to_document)
    
  3. To modify the background color of a table cell, you need to access the cell_format object and set the shading attribute to the desired color:

    cell = document.tables[table_index].cell(row_index, col_index)
    cell_format = cell._element.xpath('.//w:tcPr/w:shd')[0]._element
    cell_format.set('fill', '00ff00')  # set to green
    
  4. Similarly, to modify the text color of a table cell, you need to access the paragraph_format object and set the font.color.rgb attribute to the desired color:

    cell_paragraph = cell.paragraphs[0]
    cell_paragraph_format = cell_paragraph.paragraph_format
    cell_paragraph_format.font.color.rgb = RGBColor(255, 0, 0)  # set to red
    
  5. Finally, you need to save the document:

    document.save(path_to_document)
    

Note that the table_index, row_index, and col_index parameters are zero-based indices, i.e., the first table has index 0, the first row has index 0, and the first column has index 0.