在0.8.8之前的版本中创建页眉和页脚 [英] Header and footer creation in versions before 0.8.8

查看:128
本文介绍了在0.8.8之前的版本中创建页眉和页脚的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在用于在Microsoft Word(docx)文件中添加页眉和页脚的解决方法?

Is there a workaround for adding headers and footers in a Microsoft Word (docx) file?

python-docx 之前0.8.8的版本中未实现这些功能.

These are not implemented in versions of python-docx prior to 0.8.8.

更具体地说,我想添加:

More specifically, I would like to add:

  1. 页脚的页码
  2. 一些随机文本到标题

理想的代码如下所示:

The ideal code will look as follows:

from docx import Document

document = Document()

# Add header and footer on all pages

document.save("demo.docx")

推荐答案

这样的事情怎么样(感谢Eliot K)

How about something like this (Thanks to Eliot K)

from docx import Document
import win32com.client as win32
import os.path
import tempfile

tempdir = tempfile.gettempdir()
msword = win32.gencache.EnsureDispatch('Word.Application')
tempfile = os.path.join(tempdir, "temp.doc")

document = Document()

document.save(tempfile)

doc = msword.Documents.Open(tempfile)

doc.Sections(1).Footers(1).Range.Text = r'Text to be included'
doc.Sections(1).Footers(1).PageNumbers.Add()
doc.SaveAs(tempfile, FileFormat = 0)

document = Document(tempfile)

也许不是最优雅的方法,但是应该做您需要的事情. 也许将丑陋的保存/加载代码隔离在代码尘土飞扬的角落中的某个函数中;-)

Not the most elegant approach perhaps, but should do what you need it to. Maybe sequester the ugly save/load code in a function somewhere in a dusty corner of your code ;-)

同样,确实需要装有Microsoft Office的Windows计算机.

Again, does require a windows machine with microsoft office installed.

祝你好运!

这篇关于在0.8.8之前的版本中创建页眉和页脚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆