【问题标题】:How do I change the line thickness in a table using python docx如何使用 python docx 更改表格中的线条粗细
【发布时间】:2022-10-31 16:42:12
【问题描述】:

Line thickness 1 within a table

Line thickness 2 within a table

我目前正在尝试更改 Microsoft Word 文档中表格的线条粗细。该表的默认线条粗细为 1 pt,我正在尝试找到一种使用 python docx 将线条粗细更改为 2pt 的方法。

【问题讨论】:

  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如它目前所写的那样,很难准确地说出你在问什么。

标签: python ms-word python-docx


【解决方案1】:

此处提供设置表格/单元格边框的文档:http://officeopenxml.com/WPtableBorders.php

我已经重用了现有的代码来设置表格单元格边框在这里回答https://stackoverflow.com/a/49615968/5736491 并修改它以设置单个表格属性。这将为表格中的所有边框设置统一属性,并将其存储在表格级别(而不是单个单元格级别):

from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.table import Table
from docx import Document

def set_table_border(table: Table, **kwargs):
    """
    Sets table border
    Usage:

    set_table_border(
        table,
        top={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
        bottom={"sz": 12, "color": "#00FF00", "val": "single"},
        start={"sz": 24, "val": "dashed", "shadow": "true"},
        end={"sz": 12, "val": "dashed"},
    )
    """
    tbl  = table._tbl
    tblPr = tbl.tblPr

    # check for tag existnace, if none found, then create one
    tblBorders = tblPr.first_child_found_in("w:tblBorders")
    if tblBorders is None:
        tblBorders = OxmlElement('w:tblBorders')
        tblPr.append(tblBorders)

    # list over all available tags
    for edge in ('start', 'top', 'end', 'bottom', 'insideH', 'insideV'):
        edge_data = kwargs.get(edge)
        if edge_data:
            tag = 'w:{}'.format(edge)

            # check for tag existnace, if none found, then create one
            element = tblBorders.find(qn(tag))
            if element is None:
                element = OxmlElement(tag)
                tblBorders.append(element)

            # looks like order of attributes is important
            for key in ["sz", "val", "color", "space", "shadow"]:
                if key in edge_data:
                    element.set(qn('w:{}'.format(key)), str(edge_data[key]))

if __name__ == "__main__":
    doc = Document()
    t = doc.add_table(rows=1, cols=3)

    border_prop = {
        'sz': '16', # table border thickness (8=1pt => 16 = 2pt)
        'val': 'single', # line style
        'color': 'auto' # border color
    }
    set_table_border(t, top=border_prop, bottom=border_prop,
                        end=border_prop, start=border_prop,
                        insideH=border_prop, insideV=border_prop)

    doc.save('borders.docx')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    • 2011-02-02
    • 2022-07-05
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多