python批量修改word文档,替换word文档文字

之前写了一个python脚本,用于姜数据库中的数据批量写入到word模板中,生成很多份报告。

但是模板并不是万能的,有时候会因为某个填充的数据为空导致那句话没有用,需要删掉或者微调。

因此,需要再写一个python文件做一个批量的修改。这里我用到了python中的docx这个库。

doc = docx.Document(‘xxx.docx’)
for p in doc.paragraphs:
    tmp = ‘’
    runs = p.runs
    for i, run in enumerate(runs):
        if run.text:
            tmp += run.text
            if 'xxx' in tmp:
               run.text = run.text.replace(run.text, tmp)
               run.text = run.text.replace(‘xxx’, '替换后的字符串')
               tmp = ''
doc.save('xxx.docx')

后来又发现了一个问题,word文本框中的文章是替换不了的,经过检索(百度)可以这样实现文本框内的文字修改:

document = Document('xxx.docx')
children = document.element.body.iter()
for child in children:
    if child.tag.endswith('txbx'): 
        for ci in child.iter():
            if ci.tag.endswith('main}t'):
                if '要修改的文字' in ci.text:
                    ci.text = '修改后的文字'
 document.save('xxx.docx')

 参考python修改word文本框中的内容_python改变输入框内容_zwy_0309的博客-CSDN博客

Python批量提取docx格式Word文档中所有文本框内的文本

 我本来想用

ci.text.replace('xxx','xxxx')

但是这种方法行不通,有大佬知道的话告诉我一声,谢谢!

你可能感兴趣的:(office,python,word,数据库)