Python docx添加表格后,对表格首行设置背景色

用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

 

  • 7
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
设置 python-docx 表格背景色,可以使用 `table.style` 属性来设置表格的样式,然后使用 `TableStyle` 对象来设置背景色。具体步骤如下: 1. 导入必要的模块: ```python from docx import Document from docx.shared import RGBColor from docx.oxml.ns import qn from docx.oxml import OxmlElement from docx.enum.table import WD_TABLE_ALIGNMENT from docx.enum.text import WD_ALIGN_PARAGRAPH ``` 2. 创建文档对象和表格对象: ```python document = Document() table = document.add_table(rows=3, cols=3) ``` 3. 设置表格样式: ```python table.style = 'Table Grid' ``` 4. 定义一个函数来设置表格背景色: ```python def set_cell_background_color(cell, color): """设置表格单元格背景色""" cell._element.clear_content() tcPr = OxmlElement('w:tcPr') cell._element.append(tcPr) tcW = OxmlElement('w:tcW') tcW.set(qn('w:w'), '0') tcW.set(qn('w:type'), 'auto') tcPr.append(tcW) shd = OxmlElement('w:shd') shd.set(qn('w:fill'), color) shd.set(qn('w:val'), 'clear') tcPr.append(shd) ``` 5. 使用上面定义的函数设置单元格背景色: ```python set_cell_background_color(table.cell(0, 0), RGBColor(255, 0, 0)) # 设置第一行第一列单元格背景色为红色 set_cell_background_color(table.cell(1, 1), RGBColor(0, 255, 0)) # 设置第二行第二列单元格背景色为绿色 set_cell_background_color(table.cell(2, 2), RGBColor(0, 0, 255)) # 设置第三行第三列单元格背景色为蓝色 ``` 6. 最后保存文档: ```python document.save('table.docx') ``` 注意:上面定义的 `set_cell_background_color()` 函数中的 `cell._element.clear_content()` 表示清空单元格原有的内容,如果需要保留原有内容,请删除此行代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值