[试图用下面的代码在python-docx
中减小段落之间的间距,但是将格式应用于该段落时,最后一段会缩小,但各段之间的行不会减少。
我在link 1和link 2处找到了一些示例,但他们不理解xml
部分无法获得所需的结果。
我需要您的帮助,以通过python减小段落之间的间距,但不通过word文件进行设置。
from docx import Document
from docx.shared import Inches
from docx.enum.style import WD_STYLE_TYPE
from docx.shared import Pt
document = Document()
document.add_heading('THIS IS MY HEADER WANT TO UNDERLINE IT')
paragraph = document.add_paragraph('THIS IS MY FIRST PARAGRAPH ')
paragraph = document.add_paragraph('THIS IS SECOND PARAGRAPH')
paragraph = document.add_paragraph('SPACING BETWEEN EACH SHOULD BE DECREASED')
paragraph_format = paragraph.paragraph_format
paragraph_format.line_spacing = Pt(3)
paragraph_format.space_after = Pt(5)
print("document created")
document.save('demo.docx')
如果您检查生成的Word文件,您可以按照声明的方式精确地查看您的代码。最后一段-您唯一将格式应用于的段-行距为3pt,后跟5pt;其他所有段落均以默认格式显示。
所以python-docx
正常工作,并且如果您的输出错误,那是因为您的代码错误。
首先,我强烈建议您不要将行距设置为3 pt;我认为您很困惑,因为它“无法正常工作”,而您打算设置space_before
。其次,确保将格式应用于all段落,而不仅仅是最后一段:
from docx import Document
from docx.shared import Pt
document = Document()
document.add_heading('THIS IS MY HEADER WANT TO UNDERLINE IT')
paragraph = document.add_paragraph('THIS IS MY FIRST PARAGRAPH ')
paragraph.paragraph_format.space_before = Pt(3)
paragraph.paragraph_format.space_after = Pt(5)
paragraph = document.add_paragraph('THIS IS SECOND PARAGRAPH')
paragraph.paragraph_format.space_before = Pt(3)
paragraph.paragraph_format.space_after = Pt(5)
paragraph = document.add_paragraph('SPACING BETWEEN EACH SHOULD BE DECREASED')
paragraph.paragraph_format.space_before = Pt(3)
# no need to set space_after because there is no text after this
print("document created")
document.save('demo.docx')
这将导致文档的所有三个文本段落在其之前有3磅的多余空间,在其后有5磅(并带有规则的前导)。