如何使用python-docx库设置表格单元格的边框(How to setup cell borders with python-docx)

1.在用python-docx库插入表格后,想要更改表格样式可以通过表格样式来更改,比如:设为无线框表格

table_style = 'Normal Table'

这种方法在网上一堆,便不再赘述。但这种方法很“死板”,只能选取docx库中的指定样式,做不到根据要求隐去表格的某条边框,要实现此功能,只能自己写。

2.python-docx库官方目前没有设置单元格边框的函数方法,可以使用下列代码进行每个单元格边框的设置,用法见函数中‘Usage’字段。

​from docx.table import _Cell
from docx.oxml import OxmlElement
from docx.oxml.ns import qn

def set_cell_border(cell: _Cell, **kwargs):
    """
    Set cell`s border
    Usage:

    set_cell_border(
        cell,
        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"},
    )
    """
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()

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

    # 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 = tcBorders.find(qn(tag))
            if element is None:
                element = OxmlElement(tag)
                tcBorders.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]))

​

 3. Check http://officeopenxml.com/WPtableBorders.php for available attributes values

Elements:

ElementDescription
topSpecifies the border displayed at the top of the cell.

Reference: ECMA-376, 3rd Edition (June, 2011), Fundamentals and Markup Language Reference § 17.4.75.

bottomSpecifies the border displayed at the bottom of a cell.

Reference: ECMA-376, 3rd Edition (June, 2011), Fundamentals and Markup Language Reference § 17.4.3.

startSpecifies the border displayed on the leading edge of the cell (left for left-to-right tables and right for right-to-left tables).

Note: In the previous version of the standard, this element was left.

Reference: ECMA-376, 3rd Edition (June, 2011), Fundamentals and Markup Language Reference § 17.4.34.

endSpecifies the border displayed on the trailing edge of the cell (right for left-to-right tables and left for right-to-left tables).

Note: In the previous version of the standard, this element was right.

Reference: ECMA-376, 3rd Edition (June, 2011), Fundamentals and Markup Language Reference § 17.4.12.

insideHSpecifies the border to be displayed on all interior horizontal edges of the cell. Note that this is mostly useless in the case of individual cells, as there is no concept of interior edge for individual cells. However, it is used to determine cell borders to apply to a specific group of cells as part of table conditional formatting in a table style, e.g., the inside edges on the set of cells in the first column.

Reference: ECMA-376, 3rd Edition (June, 2011), Fundamentals and Markup Language Reference § 17.4.24.

insideVSpecifies the border to be displayed on all interior vertical edges of the cell. Note that this is mostly useless in the case of individual cells, as there is no concept of interior edge for individual cells. However, it is used to determine cell borders to apply to a specific group of cells as part of table conditional formatting in a table style, e.g., the inside edges on the set of cells in the first column.

Reference: ECMA-376, 3rd Edition (June, 2011), Fundamentals and Markup Language Reference § 17.4.26.

tl2brSpecifies the border to be displayed on the top left side to bottom right diagonal within the cell.

Reference: ECMA-376, 3rd Edition (June, 2011), Fundamentals and Markup Language Reference § 17.4.74.

tr2blSpecifies the border to be displayed on the top right to bottom left diagonal within the cell.

Reference: ECMA-376, 3rd Edition (June, 2011), Fundamentals and Markup Language Reference § 17.4.80.

Attributes of child elements:

The most commonly used attributes are below. (The theme-related and frame attributes have been omitted.)

AttributeDescription
colorSpecifies the color of the border. Values are given as hex values (in RRGGBB format). No #, unlike hex values in HTML/CSS. E.g., color="FFFF00". A value of auto is also permitted and will allow the consuming word processor to determine the color.
shadowSpecifies whether the border should be modified to create the appearance of a shadow. For right and bottom borders, this is done by duplicating the border below and right of the normal location. For the right and top borders, this is done by moving the border down and to the right of the original location. Permitted values are true and false.
spaceSpecifies the spacing offset. Values are specified in points (1/72nd of an inch).
szSpecifies the width of the border. Table borders are line borders (see the val attribute below), and so the width is specified in eighths of a point, with a minimum value of two (1/4 of a point) and a maximum value of 96 (twelve points). (Page borders can alternatively be art borders, with the width is given in points and a minimum of 1 and a maximum of 31.)
valSpecifies the style of the border. Table borders can be only line borders. (Page borders can also be art borders.) Possible values are:
  • single - a single line
  • dashDotStroked - a line with a series of alternating thin and thick strokes
  • dashed - a dashed line
  • dashSmallGap - a dashed line with small gaps
  • dotDash - a line with alternating dots and dashes
  • dotDotDash - a line with a repeating dot - dot - dash sequence
  • dotted - a dotted line
  • double - a double line
  • doubleWave - a double wavy line
  • inset - an inset set of lines
  • nil - no border
  • none - no border
  • outset - an outset set of lines
  • thick - a single line
  • thickThinLargeGap - a thick line contained within a thin line with a large-sized intermediate gap
  • thickThinMediumGap - a thick line contained within a thin line with a medium-sized intermediate gap
  • thickThinSmallGap - a thick line contained within a thin line with a small intermediate gap
  • thinThickLargeGap - a thin line contained within a thick line with a large-sized intermediate gap
  • thinThickMediumGap - a thick line contained within a thin line with a medium-sized intermediate gap
  • thinThickSmallGap - a thick line contained within a thin line with a small intermediate gap
  • thinThickThinLargeGap - a thin-thick-thin line with a large gap
  • thinThickThinMediumGap - a thin-thick-thin line with a medium gap
  • thinThickThinSmallGap - a thin-thick-thin line with a small gap
  • threeDEmboss - a three-staged gradient line, getting darker towards the paragraph
  • threeDEngrave - a three-staged gradient like, getting darker away from the paragraph
  • triple - a triple line
  • wave - a wavy line

Reference: ECMA-376, 3rd Edition (June, 2011), Fundamentals and Markup Language Reference § 17.18.2.

  • 10
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值