在Word[docx][Python 3.8.2]中设置表格单元格的背景色
我在理解如何设置表格单元格的背景色时遇到问题 我尝试了许多组合,但我唯一能做的就是设置段落风格在Word[docx][Python 3.8.2]中设置表格单元格的背景色,python,ms-word,docx,python-docx,Python,Ms Word,Docx,Python Docx,我在理解如何设置表格单元格的背景色时遇到问题 我尝试了许多组合,但我唯一能做的就是设置段落风格 import docx doc = docx.Document() records = ( (3, '101', 'Spam'), (7, '422', 'Eggs'), (4, '631', 'Spam, spam, eggs, and spam') ) table = doc.add_table(rows=1, cols=3) hdr_cells =
import docx
doc = docx.Document()
records = (
(3, '101', 'Spam'),
(7, '422', 'Eggs'),
(4, '631', 'Spam, spam, eggs, and spam')
)
table = doc.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for qty, id, desc in records:
row_cells = table.add_row().cells
row_cells[0].add_paragraph(str(qty), "Title 1")
row_cells[0].text_frame.paragraph[0].font.size = Pt(12)
row_cells[1].text = id
row_cells[2].text = desc
doc.save("Testing.docx")
我想将行单元格[0]设置为红色背景,但无法设置
我该怎么做呢?官方python docx库仍然不支持该选项。 但是,您可以尝试自己实现它。您要查找的属性称为位于下 解决方案: 将着色元素(
w:shd
)添加到单元格属性(w:tcPr
)
编写了一个简单的函数,它可以实现以下功能:
def _set_cell_background(cell, fill, color=None, val=None):
"""
@fill: Specifies the color to be used for the background
@color: Specifies the color to be used for any foreground
pattern specified with the val attribute
@val: Specifies the pattern to be used to lay the pattern
color over the background color.
"""
from docx.oxml.shared import qn # feel free to move these out
from docx.oxml.xmlchemy import OxmlElement
cell_properties = cell._element.tcPr
try:
cell_shading = cell_properties.xpath('w:shd')[0] # in case there's already shading
except IndexError:
cell_shading = OxmlElement('w:shd') # add new w:shd element to it
if fill:
cell_shading.set(qn('w:fill'), fill) # set fill property, respecting namespace
if color:
pass # TODO
if val:
pass # TODO
cell_properties.append(cell_shading) # finally extend cell props with shading element
如果需要,可以随意扩展其他属性
因此,根据您的示例,一旦有了表,在保存文档之前,请添加以下行:
.
.
_set_cell_background(table.rows[0].cells[0], 'FF0000')
doc.save("Testing.docx")
此外,请在此处注册此新元素,为官方图书馆捐款:。)
希望这有帮助