由于工作需要,需要批量处理文档,利用python-docx,配合简单的图形页面(本人用的是pyqt5),可以创建出许多得心应手的小程序,转换成exe后,也很适合推广使用。

在处理文档时,替换段落中的指定内容比较容易,但是在替换word中的表格时,常规处理会改变其格式,处理思路是将将每一格当作一个段落来处理。代码如下:

from docx import Document

def read_ducment(old,new):
    # 遍历文档
    for paragraph in document.paragraphs:
        for run in paragraph.runs:
            #替换功能
            if old in run.text:
                run.text=run.text.replace(old,new)

    # 遍历表格
    for table in document.tables:
        for row in table.rows:
            for cell in row.cells:
                #遍历表格段落内容,回到上个步骤,将cell当作paragraph处理
                for paragraph in cell.paragraphs:
                    for run in paragraph.runs:
                        #替换功能
                        if old in cell.text:
                            run.text=run.text.replace(old,new)


document=Document('123.docx')
read_ducment('需替换','要换成')
document.save('new.docx')
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐