python docx设置表格单元格背景和文本颜色

Yeb*_*ach 7 python docx cell python-docx

我正在使用带有docx的python 2.7,我想根据条件更改表格中单元格的背景和文本颜色.

我找不到任何关于单格格式化的有用资源

有什么建议?

编辑1

我的代码

style_footer = "DarkList"
style_red = "ColorfulList"
style_yellow = "LightShading"
style_green = "MediumShading2-Accent6"
style_transperent = "TableNormal"
for a,rec in enumerate(data):
    #V headinh se piše prvo polje iz table heada
    document.add_heading(rec['tableHead'][0][0], level=1)
    image_path = imageFolder + "\\" + slike[a]
    document.add_picture(image_path, height=Inches(3.5))

    #y += 28
    #worksheet.insert_image( y, 1,imageFolder + "/" + slike[a])


    for i, head in enumerate(rec['tableHead']):
        table = document.add_table(rows=1, cols = len(head))
        hdr_cells = table.rows[0].cells
        for a in range(0,len(head)):
            hdr_cells[a].text = head[a] 


    for a,body in enumerate(rec['tableData']):
        row_cells = table.add_row().cells

        for a in range(0,len(body)):
            if body[a]['style'] == 'footer':
                stil = style_footer
            elif body[a]['style'] == 'red':
                stil = style_red

            elif body[a]['style'] == 'yellow':
                stil = style_yellow
            elif body[a]['style'] == 'green':
                stil = style_green

            else:
                stil = style_transperent

            row_cells[a].add_paragraph(body[a]['value'], stil)

document.save(wordDoc)
Run Code Online (Sandbox Code Playgroud)

所有细胞仍然相同.

Nik*_*ris 11

如果要为表中的特定单元格填充颜色,可以使用下面的代码.例如,假设您需要使用RGB颜色1F5C8B填充表格第一行中的第一个单元格:

from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml

shading_elm_1 = parse_xml(r'<w:shd {} w:fill="1F5C8B"/>'.format(nsdecls('w')))
table.rows[0].cells[0]._tc.get_or_add_tcPr().append(shading_elm_1)
Run Code Online (Sandbox Code Playgroud)

现在,如果你想用相同的颜色填充第一行中的第二个单元格,你应该创建一个新元素,否则如果你使用与上面相同的元素,填充将继续,并将从第一个单元格中消失...

shading_elm_2 = parse_xml(r'<w:shd {} w:fill="1F5C8B"/>'.format(nsdecls('w')))
table.rows[0].cells[1]._tc.get_or_add_tcPr().append(shading_elm_2)
Run Code Online (Sandbox Code Playgroud)

...等等其他细胞.

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


小智 7

使用 Nikos Tavoularis 的解决方案,我们必须为每个单元创建一个新元素。我创建了一个函数来实现这一点。适用于 Python 修订版 3.5.6 和 python-docx 修订版 0.8.10

from docx.oxml import OxmlElement
from docx.oxml.ns import qn

def set_table_header_bg_color(table.rows[row_ix].cell):
    """
    set background shading for Header Rows
    """
    tblCell = cell._tc
    tblCellProperties = tblCell.get_or_add_tcPr()
    clShading = OxmlElement('w:shd')
    clShading.set(qn('w:fill'), "00519E") #Hex of Dark Blue Shade {R:0x00, G:0x51, B:0x9E}
    tblCellProperties.append(clShading)
    return cell
"""
End of set_table_header_bg_color Function
"""
# main function
"""
..
..
..
1. Load Document
..
2. Access the required section
..
3. Load the required Table
..
4. Traverse to the cell by accessing the rows object
..
"""
for each_row in table.rows :
    for each_cell in each_row.cells:
        if each_cell.value satisfies a condition:
            set_table_header_bg_color(each_cell)
"""
5. Continue execution
"""
Run Code Online (Sandbox Code Playgroud)


Ste*_*nes 4

看起来cell.text = "Something"您需要使用而不是使用方法cell.add_paragraph("SomeText", a_style)定义的样式 - 可能是以下之一:

\n\n
    \n
  • 彩色网格
  • \n
  • 彩色网格-Accent1
  • \n
  • 彩色网格-Accent2
  • \n
  • 彩色网格-Accent3
  • \n
  • 彩色网格-Accent4
  • \n
  • 彩色网格-Accent5
  • \n
  • 彩色网格-Accent6
  • \n
\n\n

完整列表在这里

\n\n

如果您使用 \xe2\x80\x9cdefault\xe2\x80\x9d 模板文档 - 否则您将必须创建自己的模板文档。

\n