How do I change the font color in the cell under the table in the Word document?

Question:

I tried to use document.styles['Normal'].font.color.rgb = RGBColor(255, 0, 255) to change the font color in the table, but it made all of the colors change in the fonts of the table. Am I missing something?

import docx
from docx.shared import RGBColor

# Create Table
document = docx.Document()
table = document.add_table(rows=2, cols=2)
table.style = 'Table Grid'

#Change the font Color to Blue
document.styles['Normal'].font.color.rgb = RGBColor(50, 0, 255)  # Blue Color
document.tables[0].rows[0].cells[0].text = "Blue"

#Change the font Color to Red
document.styles['Normal'].font.color.rgb = RGBColor(255, 0, 0)  # Red Color
document.tables[0].rows[1].cells[1].text = "Red"

document.save('result.docx')

After execution, the outcome is below:

enter image description here

Hope the result of the execution is below:

enter image description here

Asked By: wasicat

||

Answers:

According to this post, you can set the cell color directly after you get the paragraph object.

# Change the font Color to Blue. 
document.tables[0].rows[0].cells[0].paragraphs[0].runs[0].font.color.rgb = RGBColor(50, 0, 255)  # Blue Color
document.tables[0].rows[0].cells[0].text = "Blue"
Answered By: tresf
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.