使用Python的docx库,如何缩进表格?

时间:2018-05-27 21:19:49

标签: python python-docx

docx表如何缩进?我正在尝试使用设置为2cm的制表位排列一张桌子。以下脚本创建标题,一些文本和表格:

import docx
from docx.shared import Cm

doc = docx.Document()

style = doc.styles['Normal']
style.paragraph_format.tab_stops.add_tab_stop(Cm(2))

doc.add_paragraph('My header', style='Heading 1')
doc.add_paragraph('\tText is tabbed')

# This indents the paragraph inside, not the table
# style = doc.styles['Table Grid']
# style.paragraph_format.left_indent = Cm(2)

table = doc.add_table(rows=0, cols=2, style="Table Grid")

for rowy in range(1, 5):
    row_cells = table.add_row().cells

    row_cells[0].text = 'Row {}'.format(rowy)
    row_cells[0].width = Cm(5)

    row_cells[1].text = ''
    row_cells[1].width = Cm(1.2)

doc.save('output.docx')

它生成一个没有ident的表,如下所示:

no indent

表格如何缩进如下?
(最好不必加载现有文件):

Desired output

例如,如果将left-indent添加到Table Grid样式(通过取消注释行),它将应用于段落级别,而不是表级别,从而导致以下内容(不需要):

indented at paragraph level

在Microsoft Word中,可以通过为2.0 cm输入Indent from left来对表格属性执行此操作。

3 个答案:

答案 0 :(得分:1)

docs/notebooks尚不支持此功能。看起来这种行为是由python-docx元素的w:tblInd子元素生成的。您可以开发一个变通方法函数,使用w:tbl元素上的lxml调用添加这样的元素,该元素应该在w:tbl对象的._element属性上可用

您可以通过搜索“python-docx变通方法函数”来查找“python-docx变通方法函数”以及类似函数来找到其他变通办法函数的示例。

答案 1 :(得分:1)

这是我的做法:

import docx
import lxml
mydoc = docx.Document()            
mytab = self.mydoc.add_table(3,3)
nsmap=mytab._element[0].nsmap # For namespaces
searchtag='{%s}tblPr' % nsmap['w'] # w:tblPr
mytag='{%s}tblInd' % nsmap['w'] # w:tblInd
myw='{%s}w' % nsmap['w'] # w:w
mytype='{%s}type' % nsmap['w'] # w:type
for elt in mytab._element:
    if elt.tag == searchtag:
        myelt=lxml.etree.Element(mytag)
        myelt.set(myw,'1000')
        myelt.set(mytype,'dxa')
        myelt=elt.append(myelt)

答案 2 :(得分:1)

基于Fred C's answer,我想出了以下解决方案:

from docx.oxml import OxmlElement
from docx.oxml.ns import qn

def indent_table(table, indent):
    # noinspection PyProtectedMember
    tbl_pr = table._element.xpath('w:tblPr')
    if tbl_pr:
        e = OxmlElement('w:tblInd')
        e.set(qn('w:w'), str(indent))
        e.set(qn('w:type'), 'dxa')
        tbl_pr[0].append(e)