如果使用p = doc.add_paragraph('内容', style='List Number')
来创建序号段落,会发现设置序号段落之间的段前、段后以及段落间距无法生效。后来将docx库生成的word文档打开后发现段落的设置出现问题,如下图红框所示,将该选项去掉即可使段落间距属性生效
所以经过查看XML,在word/document.xml
中的对应标签设置为
def SetContextualSpacing(p):
'''
设置段落上下文设置不相关,以使段后、段前距离等设置生效
'''
pPr = p._element.find(qn('w:pPr'))
if pPr is None:
pPr = OxmlElement('w:pPr')
contextual_setting = OxmlElement('w:contextualSpacing')
contextual_setting.set(qn('w:val'), '0')
pPr.append(contextual_setting)
# 通过调整pt来设置段落的段前距离
def SetParagraphSpaceBeforeByPt(paragraph, pt) -> None:
paragraph.paragraph_format.space_before = Pt(pt)
doc = Document()
p = doc.add_paragraph('123', style='List Number')
p = doc.add_paragraph('12345', style='List Number')
SetContextualSpacing(p=p)
SetParagraphSpaceBeforeByPt(paragraph=p, pt=35)
# 保存文档
doc.save('./test-table-updated.docx')