编辑Word文档,添加页眉/页脚并保存 - Python

时间:2013-07-22 09:16:45

标签: python-2.7 ms-word docx

我想在word文档的每个页面添加页眉和页脚,并且想要在文档的开头添加一些页面,我该如何使用python执行此操作?我已经尝试过python-docx,但它没有像我预期的那样工作。有没有其他方法可以达到我的要求?

1 个答案:

答案 0 :(得分:3)

我认为您可以采取的最佳方式是查看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-python这样的库首先提取docx,所以你可以在python 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

您可以获取docx主要内容'word / document.xml'的xmlcontent,使用docx-python进行更改(我建议您使用,docx-python似乎能够添加许多不同的内容)如果你想在文档的开头复制另一个word文档的内容,你可能会尝试将document.xml的内容复制到你的document.xml,但它可能会给你一些错误,特别是如果您使用图像或非文本内容。

要添加页眉或页脚,您必须创建文件word/header1.xmlword/footer1.xml您可以只复制您创建的文件的header1.xml内容,这应该可以。< / p>

希望这有帮助

相关问题