2

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

macropod
  • 12,757
  • 2
  • 9
  • 21
wasicat
  • 55
  • 4
  • Assuming it matches VBA, have you tried... `document.tables[0].rows[0].cells[0].font.color = RGBColor(0, 0, 255) # Blue` – tresf Sep 28 '22 at 04:39
  • @tresf after trying the suggestion, the error message shows up "AttributeError: '_Cell' object has no attribute 'font', It seems not working, – wasicat Sep 28 '22 at 05:30
  • Ok, according to this article, you will need to get the paragraph first. Does this work? https://stackoverflow.com/a/43012326/3196753 – tresf Sep 28 '22 at 06:13

1 Answers1

2

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"
tresf
  • 7,103
  • 6
  • 40
  • 101