2017-01-08 85 views
-1

我有一个问题: 如何在* .docx文件中添加标题(和页脚)? 我在我的django项目中使用库python-docx。但它真的不能添加标题。 我发现使用'win32com'的堆栈(2012年7月)解决方案,但现在它不适用于我。 帮我咨询。 谢谢。 祝您有愉快的一天。使用python在* .docx文件中添加标题

+0

试试win32com解决方案,应该很简单;并发布你的代码和什么不工作,我会看看我是否可以找到问题。 – Schollii

回答

0

Courtest of edi9999 我认为你可以采取的最好的方法是看python-docx看看它是如何管理文件。 DOCX是一种压缩格式(Docx Tag Wiki):

.docx格式是包含以下文件夹压缩文件:

+--docProps 
| + app.xml 
| \ core.xml 
+ res.log 
+--word //this folder contains most of the files that control the content of the document 
| + document.xml //Is the actual content of the document 
| + endnotes.xml 
| + fontTable.xml 
| + footer1.xml //Containst the elements in the footer of the document 
| + footnotes.xml 
| +--media //This folder contains all images embedded in the word 
| | \ image1.jpeg 
| + settings.xml 
| + styles.xml 
| + stylesWithEffects.xml 
| +--theme 
| | \ theme1.xml 
| + webSettings.xml 
| \--_rels 
|  \ document.xml.rels //this document tells word where the images are situated 
+ [Content_Types].xml 
\--_rels 
    \ .rels 

起初的docx例如DOCX,蟒蛇提取物库,因此你会发现它在蟒蛇的docx:我发现它给你:https://github.com/mikemaccana/python-docx/blob/master/docx.py#L65

def opendocx(file): 
    '''Open a docx file, return a document XML tree''' 
    mydoc = zipfile.ZipFile(file) 
    xmlcontent = mydoc.read('word/document.xml') 
    document = etree.fromstring(xmlcontent) 
    return document 

你可以得到“字/ document.xml中”,这是DOCX的主要内容xmlcontent,使用的docx的Python改变它是(我向你推荐,docx- python似乎能够添加许多不同的元素。如果您想在文档的开头复制另一个word文档的内容,您可以尝试将document.xml的内容复制到document.xml中,但它可能会给您一些错误,特别是如果您使用图片或非文字内容。

要添加页眉或页脚,您必须创建一个文件word/header1.xmlword/footer1.xml您可以复制创建的文件的header1.xml内容,这应该起作用。

希望这会有帮助

相关问题