编辑文档Python-docx标题中的内容

2024-04-25

我正在尝试查找并替换其中的文本标题中的文本框的文档。但搜索了一段时间后,似乎无法通过 python-docx 访问标题或“浮动”文本框中的内容(我读了问题here https://github.com/python-openxml/python-docx/issues/413)

所以,这意味着我们必须直接在xml格式的文档上查找和替换。你知道该怎么做吗?


我找到了解决这个问题的方法。例如,我有一个template.docx文件,我想更改其中的文本标题中的文本框如上所述。以下流程步骤,我解决了我的问题:

  1. 重新命名文件template.docx to template.zip
  2. Unzip template.zip to template folder
  3. 查找并替换我想要更改的文本之一header<number>.xml文件在/template/word/文件夹。
  4. 将所有文件压缩到/template文件夹回到template.zip
  5. Rename template.zip回到template.docx

我使用Python来操作这些

import os
import shutil
import zipfile

WORKING_DIR = os.getcwd()
TEMP_DOCX = os.path.join(WORKING_DIR, "template.docx")
TEMP_ZIP = os.path.join(WORKING_DIR, "template.zip")
TEMP_FOLDER = os.path.join(WORKING_DIR, "template")

# remove old zip file or folder template
if os.path.exists(TEMP_ZIP):
    os.remove(TEMP_ZIP)
if os.path.exists(TEMP_FOLDER):
    shutil.rmtree(TEMP_FOLDER)

# reformat template.docx's extension
os.rename(TEMP_DOCX, TEMP_ZIP)

# unzip file zip to specific folder
with zipfile.ZipFile(TEMP_ZIP, 'r') as z:
    z.extractall(TEMP_FOLDER)

# change header xml file
header_xml = os.path.join(TEMP_FOLDER, "word", "header1.xml")
xmlstring = open(header_xml, 'r', encoding='utf-8').read()
xmlstring = xmlstring.replace("#TXTB1", "Hello World!")
with open(header_xml, "wb") as f:
    f.write(xmlstring.encode("UTF-8"))

# zip temp folder to zip file
os.remove(TEMP_ZIP)
shutil.make_archive(TEMP_ZIP.replace(".zip", ""), 'zip', TEMP_FOLDER)

# rename zip file to docx
os.rename(TEMP_ZIP, TEMP_DOCX)
shutil.rmtree(TEMP_FOLDER)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

编辑文档Python-docx标题中的内容 的相关文章

随机推荐