How does python-docx color part of the text of a cell in a table in a document?

there is a table in Word. Now you want to add color to some of the text in one of the cells. How to achieve it in python-docx?

the desired effect

Sep.24,2021

it's always good to look at the document more often: python-docx.readthedocs.io/en/latest/" rel=" nofollow noreferrer "> python-docx doc
only need to get the paragraph ( paragraph ) object of the cell in the table, and modify it. For example:

from docx import Document
from docx.shared import RGBColor

document = Document()

table = document.add_table(rows=4, cols=3)
my_cell = table.cell(2, 1)
my_paragraph = my_cell.paragraphs[0]
run1 = my_paragraph.add_run('apple,')
run2 = my_paragraph.add_run('red')
red = RGBColor(255, 0, 0)
run2.font.color.rgb = red

document.save('demo.docx')

effect:


add < w:highlight WRV = "green" / >

to the part wrapped around the text.
<w:r>
  <w:rPr>
    <w:highlight w:val="green"/>
  </w:rPr>
  <w:t>Blue text on bright green background</w:t>
</w:r>
Menu