python docx set table cell background and text color

前端 未结 6 822
故里飘歌
故里飘歌 2021-01-12 20:51

I am using python 2.7 with docx and I would like to change the background and text color of cells in my table based on condition.

I could not find any usefull resour

6条回答
  •  醉酒成梦
    2021-01-12 21:23

    If you want to color fill a specific cell in a table you can use the code below. For example let's say you need to fill the first cell in the first row of your table with the RGB color 1F5C8B:

    from docx.oxml.ns import nsdecls
    from docx.oxml import parse_xml
    
    shading_elm_1 = parse_xml(r''.format(nsdecls('w')))
    table.rows[0].cells[0]._tc.get_or_add_tcPr().append(shading_elm_1)
    

    Now if you want to also fill the second cell in the first row with the same color, you should create a new element otherwise if you use the same element as above the fill will move on and will disappear from the first cell...

    shading_elm_2 = parse_xml(r''.format(nsdecls('w')))
    table.rows[0].cells[1]._tc.get_or_add_tcPr().append(shading_elm_2)
    

    ...and so on for other cells.

    Source: https://groups.google.com/forum/#!topic/python-docx/-c3OrRHA3qo

提交回复
热议问题