微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python-docx:合并外部单元格时单元格边缘消失

如何解决Python-docx:合并外部单元格时单元格边缘消失

我正在使用 python-docx 创建一个所有单元格都有边框的表格。当我合并单元格涉及外部单元格时,一些外部边界消失。我使用其他 stackoverflow 问题中的函数 - 在下面的代码显示为注释的链接 - 来设置单元格边框。如何解决这个问题,以便在合并的单元格中显示外边框?

错误的边界:

Wrong borders

良好的边框:

Good borders

工作示例:

from docx import Document
from docx.oxml.shared import OxmlElement,qn


# from https://stackoverflow.com/questions/33069697/how-to-setup-cell-borders-with-python-docx
def set_cell_edges(cell,edges,color,style,width):
    """
     Parameter   Type                 DeFinition
     =========== ==================== ==========================================================================================
     cell        Cell                 Cell to apply edges
     edges       str,list,None      Cell edges,options are 'top','bottom','start' and 'end'
     color       str                  Edge color
     style       str                  Edge style,options are 'single','dotted','dashed','dashdotted' and 'double',width       int,float           Edge width in points
    """
    kwargs = dict()

    for edge in edges:
        kwargs[edge] = {'sz': width,'val': style,'color': color}

    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()

    # check for tag existance,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','insideH','insideV'):
        edge_data = kwargs.get(edge)
        if edge_data:
            tag = 'w:{}'.format(edge)

            # check for tag existance,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]))


if __name__ == '__main__':

    rows = 3
    columns = 3

    document = Document()

    # create table
    table = document.add_table(rows=rows,cols=columns)

    # merge cells
    scell = table.rows[1].cells[1]
    ecell = table.rows[2].cells[2]
    scell.merge(ecell)

    # set 4 borders in all cells
    for row in table.rows:
        for cell in row.cells:
            set_cell_edges(cell,['top','start','end'],'#ff0000','single',1)

    document.save('test.docx')

当然,我可以设置额外的列和行来设置特定的边框。但是如果没有那个技巧就可以修复它会很好。技巧示例。

带有技巧的良好边框:

Good borders with tick

if __name__ == '__main__':

    rows = 3
    columns = 3

    document = Document()

    # create table
    table = document.add_table(rows=rows+1,cols=columns+1)

    # merge cells
    scell = table.rows[1].cells[1]
    ecell = table.rows[2].cells[2]
    scell.merge(ecell)

    # set 4 borders in all cells
    for row in table.rows[:-1]:
        for cell in row.cells[:-1]:
            set_cell_edges(cell,1)

    # set top border in last row
    for cell in table.rows[-1].cells[:-1]:
        set_cell_edges(cell,['top'],1)

    # set left border in last column
    for cell in table.columns[-1].cells[:-1]:
        set_cell_edges(cell,['start'],1)

    document.save('test.docx')

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。