python如何使用python-docx调整Word文档样式
作者:沉觞流年
本文介绍了如何修改文字字体样式、对齐样式、行间距以及段前段后间距,并通过效果展示给出参考,适用于需要进行文档编辑的读者
修改文字字体样式
from docx import Document from docx.shared import Pt #设置像素、缩进等 from docx.shared import RGBColor #设置字体颜色 from docx.oxml.ns import qn doc = Document(r"../wordDemo/表彰大会通知.docx") for paragraph in doc.paragraphs: for run in 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.paragraphs: 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) # 段前 paragraph.paragraph_format.space_after = Pt(10) # 段后 # Pt(12) 表示12磅 doc.save(r"../wordDemo/test.docx")
效果展示
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。