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()
win32com为word添加页码(示例)
最新推荐文章于 2023-12-01 14:13:14 发布