Text-Replace in docx and save the changed file with python-docx

前端 未结 8 851
小鲜肉
小鲜肉 2021-01-02 07:04

I\'m trying to use the python-docx module to replace a word in a file and save the new file with the caveat that the new file must have exactly the same formatting as the ol

8条回答
  •  南笙
    南笙 (楼主)
    2021-01-02 07:42

    from docx import Document
    file_path = 'C:/tmp.docx'
    document = Document(file_path)
    
    def docx_replace(doc_obj, data: dict):
        """example: data=dict(order_id=123), result: {order_id} -> 123"""
        for paragraph in doc_obj.paragraphs:
            for key, val in data.items():
                key_name = '{{{}}}'.format(key)
                if key_name in paragraph.text:
                    paragraph.text = paragraph.text.replace(key_name, str(val))
        for table in doc_obj.tables:
            for row in table.rows:
                for cell in row.cells:
                    docx_replace(cell, data)
    
    docx_replace(document, dict(order_id=123, year=2018, payer_fio='payer_fio', payer_fio1='payer_fio1'))
    document.save(file_path)
    

提交回复
热议问题