python docx 设置背景颜色 table 单元格

python docx setting background color table cell

要为 table 中的单元格设置背景颜色,我使用以下代码:

doc.add_paragraph('')
t1 = doc.add_table(rows=7, cols=2)
t1.style = 'TableGrid'
for row in range(7):
    cell = t1.cell(row, 0)
    cell._tc.get_or_add_tcPr().append(shading_elm_green)

唯一的问题是结果如下:

但我希望所有单元格都具有背景色。为什么这不设置所有单元格。另外,当我创建许多 table 时,所有单元格都是清晰的,最后一个 table 的最后一个单元格仅被设置。

我做错了什么?拜托我已经找了很多天的解决方案了!

您需要为每个单元格创建一个新的 shading_elm_green 元素。每次在当前代码中分配它时,您只是将它从一个单元格移动到下一个单元格。这就是为什么它在最后结束。

lxml API 这样有点违反直觉(直到您考虑自己如何做 :)。当您将现有元素指定为另一个元素的子元素时,例如,使用 .append()lxml 移动 元素成为该元素的子元素。如果将它附加到不同的元素,它会将它移动到那里。分配的元素不会自动 "cloned" 或类似的东西。它只能住一个地方,那个地方就是你最后"placed"它的地方。

您没有显示您的元素创建代码,但不管它是什么,将它插入到最后一行的旁边,事情应该会按您预期的方式工作。

给想知道的人举个例子


from docx import Document
from docx.shared import Inches
from docx.enum.table import WD_ALIGN_VERTICAL
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.enum.style import WD_STYLE
from docx.dml.color import ColorFormat
from docx.enum.dml import MSO_COLOR_TYPE
from docx.enum.text import WD_COLOR_INDEX
from docx.enum.text import WD_COLOR
from docx.shared import Pt
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml

document = Document()


document.add_heading('Document Title', 0)

table = document.add_table(1, 11)
table.style = 'Table Grid'
table.cell(0,1).merge(table.cell(0,4))
table.cell(0,6).merge(table.cell(0,7))
table.cell(0,9).merge(table.cell(0,10))

table.cell(0, 0).paragraphs[0].add_run("Name").bold = True
table.cell(0, 5).paragraphs[0].add_run("Offset").bold = True

table.cell(0, 1).paragraphs[0].add_run("5566")
table.cell(0, 6).paragraphs[0].add_run("never die")
table.cell(0, 9).paragraphs[0].add_run("1")
for i in range(11):
    table.cell(0, i).paragraphs[0].alignment  = WD_ALIGN_VERTICAL.CENTER

    shading_elm = parse_xml(r'<w:shd {} w:fill="D9D9D9"/>'.format(nsdecls('w')))
    #shading must create every time
    table.cell(0, i)._tc.get_or_add_tcPr().append(shading_elm)



document.add_page_break()

document.save('demo2.docx')