# -*- 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')
Python替换docx模板文件内容
最新推荐文章于 2024-07-30 10:53:26 发布