Python替换docx模板文件内容

# -*-    coding: utf-8    -*-
# File        : docx模板文件内容替换.py
# Time        : 2022-07-29 10:13
# Author      : Da
# Description : docx模板文件内容替换
import os
import shutil
import zipfile


# 解压docx文件到指定目录
def unpack(input_file, out_file):
    if os.path.exists(input_file):
        # 解压要操作的docx文件
        outZip = zipfile.ZipFile(input_file, 'r')
        for f in outZip.namelist():
            # 解压到当前目录下的out_doc文件夹下
            outZip.extract(f, out_file)
        outZip.close()
    else:
        raise FileExistsError


# 修改document.xml文件
def alter_xml(document_xml, data):
    # 读取文件的全部内容到content
    with open(document_xml, 'r', encoding='utf-8') as fp:
        content = fp.read()
    with open(document_xml, 'w', encoding='utf-8') as fp:
        for key in data:
            # 替换content中{{xx}}标记处的内容
            curr = '{{' + key + '}}'
            # 因为document里面的需要的都是str类型的数据,所以要处理一下
            content = content.replace(curr, str(data[key]))
        # 写入修改后的内容到原文件
        fp.write(content)


# 把修改好的输出文件夹重新打包成指定名字的docx文件
def pack(input, fileName):
    # 压缩指定文件夹为指定名字的docx文件
    out_zip = zipfile.ZipFile(fileName, 'w', zipfile.ZIP_DEFLATED)
    # 遍历解压输出目录
    for path, dirNames, fileNames in os.walk(input):
        # 去掉目标根路径,只对目标文件夹下边的文件及文件夹进行压缩
        fpath = path.replace(input, '')
        for f in fileNames:
            # 依次写入文件
            out_zip.write(os.path.join(path, f), os.path.join(fpath, f))
    out_zip.close()


# 替换docx文件中{{xx}}处指定的内容
def render(doc_file, data, out_file_name):
    # 暂时解压的目录
    out_path = 'doc_file_out'
    # 要操作的document.xml文件
    document_xml = out_path + '/word/document.xml'
    # 解压文件
    unpack(doc_file, out_path)
    # 修改document.xml文件
    alter_xml(document_xml, data)
    pack(out_path, out_file_name)
    # 强制删除暂时解压的目录
    shutil.rmtree(out_path, ignore_errors=True)


data = {
    'name': '测试',
    'age': 30
}

render('test.docx', data, 'ok.docx')
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值