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

标签 python cell docx python-docx

我将 python 2.7 与 docx 一起使用,我想根据条件更改表格中单元格的背景和文本颜色。

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

有什么建议吗?

编辑 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)

所有单元格仍然相同。

最佳答案

如果你想用颜色填充表格中的特定单元格,你可以使用下面的代码。 例如,假设您需要用 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)

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

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)

...其他单元格依此类推。

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

关于python docx 设置表格单元格背景和文字颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26752856/

相关文章:

python - 向前查找列表项的组合对

python - 具有继承性的 pytest 参数化 fixture - 子类没有属性

excel - 镜像片材之间的单元格范围

ios - 长按单元格时 TableView 单元格背景颜色不会改变

java - 如何在 java 中打印 .doc 和 .docx

python - 如何使用 python 从 HTML 页面中提取特定数据?

python - 如何从 Jupyter Notebook 中的 .py 文件调用函数?

ios - Xcode 调试器 : fatal error: Array index out of range. 。为什么?

xml - 我们如何将 Microsoft Word DOCX 文件转换为 XSLT 中的 HTML?

xml - 使用 AddImagePart 添加的 OpenXML 图像未显示在 document.xml.rels 中