win32com为word添加页码(示例)

from win32com.client import DispatchEx

'''
属性值、枚举参考:
参考文档:https://learn.microsoft.com/zh-cn/dotnet/api/microsoft.office.interop.word?view=word-pia
'''

w = DispatchEx('kwps.Application')                  # 连接wps接口;word.Application
w.Visible = 0                                       # 后台运行
w.DisplayAlerts = 0                                 # 不警告
filepath = ''
doc = w.Documents.Open(filepath)
w.ActiveDocument.Repaginate()
page_count = w.ActiveDocument.ComputeStatistics(2)  # 获取总页数
# 默认页码设置
# doc.Sections(1).Footers(1).PageNumbers.Add(page_count, True)
# doc.Sections(1).Footers(1).PageNumbers.NumberStyle = 48   # 样式网址:https://learn.microsoft.com/zh-cn/office/vba/api/word.wdpagenumberstyle
# doc.SaveAs(p, 12, False, "", True, "", False, False, False, False)

# 自定义页码设置
try:
    footer = doc.Sections(1).Footers(1)             # constants.wdHeaderFooterPrimary
    footer_rng = footer.Range
    footer_rng.ParagraphFormat.Alignment = 1        # 0 1 2:左中右
    footer_rng.Text = " /%d" % page_count           # 页码样式:1/2、2/2
    rng = footer_rng.Characters(1)                  # 在第一个字符的位置插入页码
    doc.Fields.Add(Range=rng, Type=33)              # Type=constants.wdFieldPage=33,有枚举类
except Exception as e:
    print(f'错误 {str(e)} {filepath}')
finally:
    doc.SaveAs(filepath, 12, False, "", True, "", False, False, False, False)
    doc.Close()
w.Quit()
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值