使用python在*.docx word文件中添加标题

使用python在*.docx word文件中添加标题,python,django,ms-word,docx,win32com,Python,Django,Ms Word,Docx,Win32com,我有一个问题: 如何在*.docx文件中添加页眉(和页脚)? 我在django项目中使用了库python docx。但它确实不能添加标题。 我在stack(2012年7月)上找到了使用“win32com”的解决方案,但现在它对我不起作用。 帮我提个建议。 非常感谢。 祝你今天愉快。 我认为最好的方法是查看pythondocx,看看它是如何管理文件的。Docx是一种压缩格式(): .docx格式是一个压缩文件,包含以下文件夹: +--docProps | + app.xml | \ cor

我有一个问题: 如何在*.docx文件中添加页眉(和页脚)? 我在django项目中使用了库python docx。但它确实不能添加标题。 我在stack(2012年7月)上找到了使用“win32com”的解决方案,但现在它对我不起作用。 帮我提个建议。 非常感谢。 祝你今天愉快。

我认为最好的方法是查看pythondocx,看看它是如何管理文件的。Docx是一种压缩格式():

.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中找到它:我为您找到了:

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

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


希望这有帮助

试试win32com解决方案,应该很简单;然后发布您的代码和不起作用的内容,我会看看是否能找到问题。
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