在python中对段落应用类似样式表的边距和颜色

在python中对段落应用类似样式表的边距和颜色,python,ms-word,styling,docx,python-docx,Python,Ms Word,Styling,Docx,Python Docx,我是python新手,谁能告诉我如何将样式表应用于段落。我添加了这样的代码 import re from docx import Document # for Word document from docx.text import Paragraph from reportlab.lib.styles import ParagraphStyle from reportlab.lib.styles import getSampleStyleSheet document.add_paragrap

我是python新手,谁能告诉我如何将样式表应用于段落。我添加了这样的代码

import re
from docx import Document # for Word document 
from docx.text import Paragraph
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.styles import getSampleStyleSheet

document.add_paragraph('My first paragraph') 

但是,当我试图使这段文字变为红色,并使用样式属性应用marginleft:20px时,它不起作用,这里有几个问题

  • 据我所知,不需要导入re,这是正则表达式库,这里没有使用
  • reportlab用于PDF文档。您不能随意地将reportlab中的样式应用于python docx文档,并期望它能够正常工作。它们是两个完全不同的图书馆
  • 段落类不打算直接实例化,因此不需要导入它
要执行您描述的操作,您可以执行以下操作:

创建一个具有所需段落样式的Word文档,如“红色缩进”,从文档中删除所有内容,并将其另存为“styled.docx”

然后:


注意:从python docx应用样式时,“红色”和“缩进”之间的空格被删除。

从docx导入文档重新导入#对于docx.text中的Word文档从reportlab.lib导入段落从reportlab.lib导入段落样式从reportlab.lib.styles导入getSampleStyleSheet从docx.enum.text导入reportlabWD_ALIGN_paragration#用于将Alignmant添加到段落document=document()p=document.add_paragration('My first paragration',style='BodyText',breakbefore=False,jc='left')p.alignment=WD_ALIGN_paragration.CENTER document.save(“MyDoc.docx”)但它会导致此错误类型错误:add_paragration()得到一个意外的关键字参数'breakbefore',将其放入问题的代码块中。像这样不可读Hey scanny根据你上面提到的评论,我应用了相同的东西,但不起作用,只是在文档文件底部添加了新添加的文本,没有任何颜色。请尝试使用“RedIndent”。我应该把字里行间的空格删掉。
document = Document('styled.docx')
paragraph = document.add_paragraph('My first paragraph')
paragraph.style = 'RedIndent'