我正在尝试查找并替换文档标题中文本框中的文本。但搜索了一段时间后,似乎无法通过 python-docx 访问标题或“浮动”文本框中的内容(我在这里阅读问题)
所以,这意味着我们必须直接在xml格式的文档上查找和替换。你知道该怎么做吗?
我找到了解决这个问题的方法。例如,我有一个template.docx文件,我想更改标题中文本框中的文本,如上所述。以下流程步骤,我解决了我的问题:
template.docx为template.ziptemplate.zip到template文件夹header<number>.xml中的文件之一中更改的文本/template/word/。/template回template.ziptemplate.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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3776 次 |
| 最近记录: |