2013-05-09 241 views
1

专家,使用python-docx搜索和替换后丢失的格式和图像

我有一个模板docx报告,其中包含图像和标准格式。我用docx做的只是搜索一些标签,并使用配置文件中的值替换它。

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

我已经搜索了关于python.docx librelist的讨论,以及他们在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') 

回答

0

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

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