使用pythondocx搜索和替换后丢失格式和图像

2024-05-19 21:56:40 发布

您现在位置:Python中文网/ 问答频道 /正文

专家们

我有一个模板docx报告,里面有图像和标准格式。我使用docx所做的只是搜索一些标记,然后使用配置文件中的值替换它。在

Search&replace按预期工作,但输出文件丢失了所有图像和格式。你知道哪里出了问题吗?我所做的只是修改这个例子-makedocument.py,并将其替换为与我的docx文件一起使用。在

我搜索了关于Python.docxlibrelist,以及他们在github上的页面,有很多类似的问题,但仍然没有得到回答。在

谢谢。在

——我的剧本就是这样简单的——

from docx import *
from ConfigParser import SafeConfigParser

filename = "template.docx"

document = opendocx(filename)
relationships = relationshiplist()
body = document.xpath('/w:document/w:body',namespaces=nsprefixes)[0]

####### get config file
parser = SafeConfigParser()
parser.read('../TESTING1-config.txt')

######## Search and replace
print 'Searching for something in a paragraph ...',
if search(body, ''):
print 'found it!'
else:
print 'nope.'

print 'Replacing ...',
body = advReplace(body, '', parser.get('ASD', 'ASD'))
print 'done.'

####### #Create our properties, contenttypes, and other support files
title = 'Python docx demo'
subject = 'A practical example of making docx from Python'
creator = 'Mike MacCana'
keywords = ['python', 'Office Open XML', 'Word']

coreprops = coreproperties(title=title, subject=subject, creator=creator,keywords=keywords)
appprops = appproperties()
contenttypes = contenttypes()
websettings = websettings()
wordrelationships = wordrelationships(relationships)

savedocx(document, coreprops, appprops, contenttypes, websettings, wordrelationships, 'Welcome to the Python docx module.docx')

Tags: from图像parsertitle格式bodydocumentsubject
2条回答

Python docx只在文档.xml文件为原始Docx zip。其他所有内容都将被丢弃并从函数或预先存在的模板文件中重新创建。不幸的是,这包括document.xml.rels文件负责映射图像的文件。在

我开发的oodocx模块复制了旧Docx的所有内容,至少在我的经验中,它可以很好地处理图像。在

我已经回答了similar question about python-docx。Python-docx并不打算存储docx图像并将其导出。在

Python-Docx不是Docx的模板引擎。在

相关问题 更多 >