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:
Hope the result of the execution is below:
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"
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:
Hope the result of the execution is below:
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"