其他分享
首页 > 其他分享> > 套用word模板

套用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')

标签:docx,word,text,套用,cell,old,run,document,模板
来源: https://www.cnblogs.com/tomhu/p/12342998.html