python如何使用python-docx调整Word文档样式
目录
- 修改文字字体样式
- 修改段落样式
- 对齐样式
- 行间距调整
- 段前与段后间距
- 总结
修改文字字体样式
from docx import Document from docx.shared import Pt #设置像素、缩进等 from docpythonx.shared import RGBColor #设置字体颜色 from docx.oXML.ns import qn doc = Document(r"../wordDemo/表彰大会通知.docx") for paragraph in doc.paragraphs: for run www.devze.comin paragraph.runs: run.font.bold = True run.font.italic = True run.font.underline = True run.font.strike = True run.font.shadow = True run.font.size = Pt(18) run.font.color.rgb = RGBColor(255,0,255) run.font.name = "黑体" # 设置编程客栈像黑体这样的中文字体,必须添加下面 2 行代码 r = run._element.rPr.rFonts r.set(qn("w:eastAsia"),"黑体") doc.save(r"../wordDemo/表彰大会通知.docx")
效果展示
修改段落样式
对齐样式
from docx import Document from docx.enum.text import WD_ALIGN_PARAGRAPH #设置对象居中、对齐等。 doc = Document(r"../wordDemo/表彰大会通知.docx") print(doc.paragraphs[1].text) doc.paragraphs[1].alignment = WD_ALIGN_PARAGRAPH.CENTER # 这里设置的是居中对齐 doc.save(r"../wordDemo/表彰大会通知.docx")
效果展示
行间距调整
from docx import Document from docx.enum.text import WD_ALIGN_PARAGRAPH doc = Document(r"../wordDemo/表彰大会通知.docx") for paragraph in doc.par编程agraphs: paragraph.paragraph_format.line_spacing = 5.0 doc.save(r"../wordDemo/表彰大会通知.docx")
效果展示
段前与段后间距
from docx import Document from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.shared import Pt doc = Document(r"../wordDemo/test.docx") for paragraph in doc.paragraphs: paragraph.paragraph_format.space_before = Pt(12) # 段前 qhQuFGa paragraph.paragraph_format.space_after = Pt(10) # 段后 # Pt(12) 表示12磅 doc.save(r"../wordDemo/test.docx")
效果展示
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。
精彩评论