python操作word文档-----调整word文档样式

from docx import Document
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.shared import Pt, RGBColor
from docx.oxml.ns import qn



doc = Document('测试.docx')
for paragraph in doc.paragraphs:
    # 段落对齐方式
    paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    # 行间距 注意用浮点数  2.0就表示两倍行间距
    paragraph.paragraph_format.line_spacing = 2.0
    # 段前与段后间距  Pt(12)表示12磅
    paragraph.paragraph_format.space_before = Pt(12)  # 段前间距
    paragraph.paragraph_format.space_after = Pt(12)  # 段后间距

    # 对文字字体样式进行修改
    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(20)
        run.font.color.rgb = RGBColor(255, 255, 0)
        run.font.name = '微软雅黑'
        r = run._element.rPr.rFonts
        r.set(qn('w:eastAsia'), '微软雅黑')

# 最后进行保存
doc.save('test.docx')

 

posted @ 2020-09-04 19:06  不会飞的鲨鱼  阅读(2156)  评论(0编辑  收藏  举报