python 在word文件的指定位置插入表格

代码内容

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)])


def move_table_after(table, paragraph):
    tbl, p = table._tbl, paragraph._p
    p.addnext(tbl)


def replace_paragraph_with_table(file_path, data, target_text, table_style=None, colorStr="87CEFA"):
    """
    指定目标段落关键字,将此段落替换为表格,表格数据格式为字典列表,第一个字典的键值为表头,表头颜色默认浅蓝色

    :param file_path: word 文件路径
    :param data: 表格数据
    :param target_text: 目标关键字
    :param table_style: 表格格式
    :param colorStr: 背景色,根据需要调整,可参考站长之家选色 http://tool.chinaz.com/Tools/PageColor.aspx
    :return:
    """
    # 打开文档
    doc = Document(file_path)

    # 查找包含特定文本的段落
    for paragraph in doc.paragraphs:
        if paragraph.text == target_text:
            # 获取字典列表中第一个字典的键作为列数
            num_cols = len(next(iter(data), {})) if data else 0
            # 在该段落的位置插入表格
            table = doc.add_table(rows=1, cols=num_cols)  # 先添加一行作为表头
            if table_style:
                table.style = table_style
            # 添加表头
            header_cells = table.rows[0].cells
            headers = list(next(iter(data), {}).keys()) if data else []
            for i, header in enumerate(headers):
                header_cells[i].text = header

            # 添加表格数据
            for item in data:
                row_cells = table.add_row().cells
                for i, key in enumerate(headers):
                    value = item.get(key, '')
                    row_cells[i].text = str(value)

            tabBgColor(table, num_cols, colorStr)
            # 将表格转移到指定位置
            move_table_after(table, paragraph)
            # 删除该关键字段落
            p = paragraph._element
            p.getparent().remove(p)
            break  # 假设只有一个匹配的段落
        else:
            print("未找到匹配段落。")
    # 保存文档
    doc.save(file_path)

此函数支持输入一个字典列表,将字典列表的数据写入到Word指定位置中,Word的指定位置由target_text关键字指明,它将会替换掉这个关键字所在的Word段落。

可以通过colorStr设置表头颜色,我喜欢浅蓝,默认写的浅蓝。

代码使用

file_path文件内容:

代码内容:

table_data是数据字典列表。

table_style指明的是表格要不要框线。

“{test_result}”是文档中的关键字,会被替换掉。

if __name__ == '__main__':
    table_data = [
        {"Name": "John", "Age": "30", "City": "New York"},
        {"Name": "Anna", "Age": "22", "City": "Los Angeles"}
    ]
    replace_paragraph_with_table("report-demo.docx",
                                 table_data, "{test_result}",
                                 'Table Grid')

结果文件内容:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值