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

时间:2018-06-07 12:34:47

标签: python python-docx

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

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)

唯一的问题是结果如下:

enter image description here

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

我做错了什么?我现在正在寻找解决方案很多天了!

2 个答案:

答案 0 :(得分:1)

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

lxml API有点违反直觉(直到你想到你将如何自己做:)。当您将现有元素指定为另一个元素的子元素时,例如,使用.append()lxml 元素移动为该元素的子元素。如果将它附加到另一个元素,它会将其移动到那里。分配的元素不会自动“克隆”或类似的东西。它只能住一个地方,那个地方就是你最后“放置”的地方。

您不会显示您的元素创建代码,但无论它是什么,请将它插入到倒数第二行,并且事情应该按您期望的方式工作。

答案 1 :(得分:-1)

给想知道的人一个例子


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')
相关问题