用python docx设置word中表格的背景色
问题来源:
https://stackoverflow.com/questions/26752856/python-docx-set-table-cell-background-and-text-color
python的docx中插入的表,设置单元个背景色时,需要每个单元格生成一个背景参数,来对表格中的单元格进行设置。
实际使用中比较冗余,现在以设置表格首行单元格背景色为例,为了简洁,通过动态变量赋值的方式实现。
代码如下:
from docx import Document
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml
# 表格首行背景色设置
def tabBgColor(table,cols,colorStr):
shading_list = locals()
for i in range(cols):
shading_list['shading_elm_'+str(i)] = parse_xml(r'<w:shd {} w:fill="{bgColor}"/>'.format(nsdecls('w'),bgColor = colorStr))
table.rows[0].cells[i]._tc.get_or_add_tcPr().append(shading_list['shading_elm_'+str(i)])
# 新建表行数
rowsNum = 3
# 新建表列数
colsNum = 3
# 背景色,根据需要调整,可参考站长之家选色 http://tool.chinaz.com/Tools/PageColor.aspx
colorStr = '6495ED'
doc = Document()
tableDemo = doc.add_table(rows=rowsNum, cols=colsNum, style='Table Grid')
tabBgColor(tableDemo, colsNum, colorStr)
doc.save('demo.docx')
运行结果截图:https://img-blog.csdnimg.cn/20200510095817404.png