使用Python在Word文档中添加页码

2 投票
2 回答
3466 浏览
提问于 2025-04-18 09:26

有没有办法用Python的win32com库在Word文档的右下角添加页码?我可以添加页眉和页脚,但找不到添加页码的方法,想要的格式是“页码/总页数”(比如:1 of 5)。

下面是用来在页面上添加居中页眉和页脚的代码。

from win32com.client import Dispatch as MakeDoc
filename = name + '.doc'
WordDoc = MakeDoc("Word.Application")
WordDoc = WordDoc.Documents.Add()
WordDoc.Sections(1).Headers(1).Range.Text = name
WordDoc.Sections(1).Headers(1).Range.ParagraphFormat.Alignment = 1
WordDoc.Sections(1).Footers(1).Range.Text = filename
WordDoc.Sections(1).Footers(1).Range.ParagraphFormat.Alignment = 1

谢谢

2 个回答

2

我知道这个问题比较老了,但我之前也为这个问题绞尽脑汁,最后找到了一种解决办法,虽然看起来不太优雅,但能解决问题。需要注意的是,在插入了 wdFieldPage 之后,我必须重新定义 activefooter,否则生成的页脚会显示成 of 12,而不是 1 of 2

当我在尝试解决格式问题时,这个关于vba的问题的答案对我很有帮助。

我使用的是Python 3.4,testdocument.doc是一个已有的.doc文件,里面有一些随机文本,分布在两页上,并且没有现成的页脚。

w = win32com.client.gencache.EnsureDispatch("Word.Application")          
w.Visible = 0
adoc = w.Documents.Open("C:\\temp1\\testdocument.doc")

activefooter = adoc.Sections(1).Footers(win32com.client.constants.wdHeaderFooterPrimary).Range
activefooter.ParagraphFormat.Alignment = win32com.client.constants.wdAlignParagraphRight
activefooter.Collapse(0)
activefooter.Fields.Add(activefooter,win32com.client.constants.wdFieldPage)
activefooter = adoc.Sections(1).Footers(win32com.client.constants.wdHeaderFooterPrimary).Range 
activefooter.Collapse(0)
activefooter.InsertAfter(Text = ' of ')
activefooter.Collapse(0)
activefooter.Fields.Add(activefooter,win32com.client.constants.wdFieldNumPages)  
adoc.Save()
adoc.Close()
w.Quit()
4

要插入页码,可以使用以下语句:

WordDoc.Sections(1).Footers(1).PageNumbers.Add(2,True)
WordDoc.Sections(1).Footers(1).PageNumbers.NumberStyle = 57

不过,页码的格式是 -页码-。关于如何插入页码的详细说明可以在这里找到,而关于数字样式的说明可以在这里查看。

撰写回答