办公自动化--python docx 表格中的文字添加高亮/背景颜色/填充颜色

文章介绍了如何使用python的docx库扩展功能,特别是针对docx库未实现的细节——高亮单元格中的文字。通过示例代码展示了如何创建文档、填充表格以及设置单元格背景色,特别地,展示了自定义函数doc_table_highlight_txt用于设置文字高亮。
摘要由CSDN通过智能技术生成

python的docx库实现了自动化需要的大部分常用的功能
但是有很多细节的功能没有实现 而且该库已经停止更新
有很多效果无法实现 如果有需要实现特定效果, 但是又找不到方法的 可以联系我
email: 491870929@qq.com

from docx import Document
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
def doc_table_highlight_txt(cell, color):
    """
    高亮单元格中的文字
    Args:
        cell:
        color:

    Returns:

    """
    shade_obj = OxmlElement('w:shd')
    shade_obj.set(qn('w:fill'), color)

    if cell._element.xpath('.//w:rPr'):
        cell._element.xpath('.//w:rPr')[0].append(shade_obj)
    else:
        a = cell.text
        cell._element.clear_content()
        p = cell.add_paragraph()
        r = p.add_run(a)
        rpr_obj = OxmlElement('w:rPr')
        rpr_obj.append(shade_obj)
        r._element.append(rpr_obj)

测试用的小demo

# 写一个小demo
# 创建文档
document = Document()
# 创建3*3表格
table = document.add_table(rows=3, cols=3, style='Table Grid')
# 填充数据
for i in range(3):
    for j in range(3):
        cell = table.cell(i, j)
        p = cell.add_paragraph()
        r = p.add_run('hello world')
        r.text = f"Row {i+1}, Column {j+1}"
        # 设置第二行第二列的单元格背景颜色为黄色(RGB 值为 (255, 255, 0))
        if i == 1 and j == 1:
            doc_table_highlight_txt(cell, 'FFFF00')
document.save('demo.docx')

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值