【问题标题】:Add page number to a Word document using Python使用 Python 将页码添加到 Word 文档
【发布时间】:2016-11-23 21:01:31
【问题描述】:

有没有办法使用 Python win32com 在 Word 文档的右下角添加页码?我可以添加页眉和页脚,但我找不到以 PageNumber of TotalPages 格式添加页码的方法(例如: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

谢谢

【问题讨论】:

  • 没关系。我想通了
  • 请将您的解决方案作为对此问题的答案发布,以便其他有相同问题的人(即我)也能解决
  • 要插入页码,请使用以下语句:WordDoc.Sections(1).Footers(1).PageNumbers.Add(2,True)WordDoc.Sections(1).Footers(1).PageNumbers.NumberStyle = 57 但是,数字的格式是 -PageNumber- 而不是我正在寻找的那个,但我很好反正
  • 谢谢,你能发帖和文档吗?
  • 当然,添加页码的文档是here,编号样式的文档是here。享受

标签: python ms-word win32com


【解决方案1】:

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

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

但是,页码的格式是-页码-。插入页码的文档是here,编号样式的文档是here

【讨论】:

    【解决方案2】:

    我知道这是一个老问题,但我正想方设法找出同样的问题,但最终想出了一个相当难看的解决方案,但完成了工作。请注意,我必须在插入 wdFieldPage 后重新定义 activefooter,否则生成的页脚将看起来像 of 12 而不是 1 of 2

    The answer to this vba question was helpful when I was trying to figure out the formatting.

    我使用的是 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()
    

    【讨论】:

      猜你喜欢
      • 2014-05-21
      • 1970-01-01
      • 1970-01-01
      • 2019-11-25
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多