如何在python-docx中将表行保持在一起?

LMc*_*LMc 10 python xml pagination python-docx

作为一个例子,我有一个通用脚本,使用python-docx输出默认表格样式(此代码运行正常):

import docx
d=docx.Document()
type_of_table=docx.enum.style.WD_STYLE_TYPE.TABLE

list_table=[['header1','header2'],['cell1','cell2'],['cell3','cell4']]
numcols=max(map(len,list_table))
numrows=len(list_table)

styles=(s for s in d.styles if s.type==type_of_table)


for stylenum,style in enumerate(styles,start=1):
    label=d.add_paragraph('{}) {}'.format(stylenum,style.name))
    label.paragraph_format.keep_with_next=True
    label.paragraph_format.space_before=docx.shared.Pt(18)
    label.paragraph_format.space_after=docx.shared.Pt(0)
    table=d.add_table(numrows,numcols)
    table.style=style
    for r,row in enumerate(list_table):
        for c,cell in enumerate(row):
            table.row_cells(r)[c].text=cell


d.save('tablestyles.docx')   
Run Code Online (Sandbox Code Playgroud)

接下来,我打开文档,突出显示拆分表并在段落格式下选择"Keep with next",这成功阻止了表格在页面中拆分:

在此输入图像描述

这是非破坏表的XML代码:

在此输入图像描述

您可以看到突出显示的行显示应该将表保持在一起的段落属性.所以我写了这个函数并将其粘贴d.save('tablestyles.docx')在行上方的代码中:

def no_table_break(document):
    tags=document.element.xpath('//w:p')
    for tag in tags:
        ppr=tag.get_or_add_pPr()
        ppr.keepNext_val=True


no_table_break(d)     
Run Code Online (Sandbox Code Playgroud)

当我检查XML代码时,段属性标记设置正确,当我打开Word文档时,将检查所有表的"保持下一个"框,但表仍然在页面之间拆分.我错过了一个XML标签或者阻止它正常工作的东西吗?

TSe*_*our 3

好的,我也需要这个。我认为我们都做出了错误的假设,即 Word 表格属性中的设置(或在 python-docx 中实现此目的的等效方法)是为了防止表格页拆分。它不是——相反,它只是关于表的行是否可以跨页拆分。

鉴于我们知道如何在 python-docx 中成功地做到这一点,我们可以通过将每个表放在较大主表的行中来防止表跨页拆分。下面的代码成功地做到了这一点。我正在使用 Python 3.6 和 Python-Docx 0.8.6

import docx
from docx.oxml.shared import OxmlElement
import os
import sys


def prevent_document_break(document):
    """https://github.com/python-openxml/python-docx/issues/245#event-621236139
       Globally prevent table cells from splitting across pages.
    """
    tags = document.element.xpath('//w:tr')
    rows = len(tags)
    for row in range(0, rows):
        tag = tags[row]  # Specify which <w:r> tag you want
        child = OxmlElement('w:cantSplit')  # Create arbitrary tag
        tag.append(child)  # Append in the new tag


d = docx.Document()
type_of_table = docx.enum.style.WD_STYLE_TYPE.TABLE

list_table = [['header1', 'header2'], ['cell1', 'cell2'], ['cell3', 'cell4']]
numcols = max(map(len, list_table))
numrows = len(list_table)

styles = (s for s in d.styles if s.type == type_of_table)

big_table = d.add_table(1, 1)
big_table.autofit = True

for stylenum, style in enumerate(styles, start=1):
    cells = big_table.add_row().cells
    label = cells[0].add_paragraph('{}) {}'.format(stylenum, style.name))
    label.paragraph_format.keep_with_next = True
    label.paragraph_format.space_before = docx.shared.Pt(18)
    label.paragraph_format.space_after = docx.shared.Pt(0)

    table = cells[0].add_table(numrows, numcols)
    table.style = style
    for r, row in enumerate(list_table):
        for c, cell in enumerate(row):
            table.row_cells(r)[c].text = cell

prevent_document_break(d)

d.save('tablestyles.docx')

# because I'm lazy...
openers = {'linux': 'libreoffice tablestyles.docx',
           'linux2': 'libreoffice tablestyles.docx',
           'darwin': 'open tablestyles.docx',
           'win32': 'start tablestyles.docx'}
os.system(openers[sys.platform])
Run Code Online (Sandbox Code Playgroud)