套用word模板

# 适合比较长的模板,并且保留原格式
from docx import Document
from docx.shared import Pt
from docx.oxml.ns import qn

document = Document(r'C:/Users/13375/Desktop/python/长恨歌2.docx')
document.styles['Normal'].font.name = u'微软雅黑'
document.styles['Normal'].element.rPr.rFonts.set(qn('w:eastAsia'),u'微软雅黑')
document.styles['Normal'].font.size = Pt(22)


def change_text(old_text,new_text):
    all_paragraphs = document.paragraphs
    for paragraph in all_paragraphs:
        for run in paragraph.runs:
            run_text = run.text.replace(old_text,new_text)
            run.text = run_text
        
    all_tables = document.tables
    for table in all_tables:
        for row in table.rows:
            for cell in row.cells:
                cell_text = cell.text.replace(old_text,new_text)
                cell.text = cell_text
                
change_text('不','OK')
change_text('女','male')

document.save(r'C:/Users/13375/Desktop/python/长恨歌修改后.docx')

上一篇:文档记录2


下一篇:doc,docx完美转html,图片保存完整代码