python在word的页脚插入页码

1、插入简易页码

python 复制代码
import win32com.client as win32
from win32com.client import constants
import os

doc_app = win32.gencache.EnsureDispatch('Word.Application')#打开word应用程序
doc_app.Visible = True

doc = doc_app.Documents.Add()
footer = doc.Sections(1).Footers(constants.wdHeaderFooterPrimary)
footer.Range.Text = "" #清空页脚内容
footer = doc.Sections(1).Footers(constants.wdHeaderFooterPrimary)
footer.LinkToPrevious = False
footer_rng = footer.Range
footer_rng.Text ="自动插入页码 "
footer.PageNumbers.Add(PageNumberAlignment=constants.wdAlignPageNumberRight, FirstPage=True)

如果存在多节的情况,可以修改footer.LinkToPrevious = True,这样页码就是连续的。

添加的页码默认是靠右对齐的。使用wdAlignPageNumberCenter,可以将页码居中。

生成效果:

2、插入自定义页码样式

有的时候,可能需要插入例如第1页,这样的页码样式。就要复杂一些了

需要在字符串"第 页"的中间插入页码。这时候需要用到Field,来实现页码。field可以有很多中作用,通过配置它的type来决定它代表什么。

python 复制代码
footer = doc.Sections(1).Footers(constants.wdHeaderFooterPrimary)
footer_rng = footer.Range
footer_rng.Text ="第   页"
rng = footer_rng.Characters(3)
doc.Fields.Add(Range=rng,Type=constants.wdFieldPage)# 在第三个字符的位置插入页码

生成效果:

添加图片注释,不超过 140 字(可选)

3、跳过目录页插入页码

当需要跳过目录页、或者封面,只在正文插入页码的时候,需要先在正文前插入分节符------让目录页或者封面与正文分别为不同的节。只对正文所在的节插入页码即可。

python 复制代码
import win32com.client as win32
from win32com.client import constants
import os

doc_app = win32.gencache.EnsureDispatch('Word.Application')#打开word应用程序
doc_app.Visible = True

doc = doc_app.Documents.Add()
parag = doc.Paragraphs.Add()
parag.Range.InsertBreak(constants.wdSectionBreakNextPage)# 在下一页插入分节符

parag = doc.Paragraphs.Add()
footer = doc.Sections(2).Footers(constants.wdHeaderFooterPrimary)
footer.Range.Text = "" # 清空页脚内容
footer = doc.Sections(2).Footers(constants.wdHeaderFooterPrimary)
footer.LinkToPrevious = False
footer_rng = footer.Range
footer_rng.Text ="自动插入页码 "
footer.LinkToPrevious = False
footer.PageNumbers.Add(PageNumberAlignment=constants.wdAlignPageNumberRight, FirstPage=True)
footer.PageNumbers.RestartNumberingAtSection = True #新的一节中,页码重新计数
footer.PageNumbers.StartingNumber = 1 # 起始页码为1

示例代码效果:

首页没有页码, ]nCVB6

第二页有插入页码,并且从1开始

相关推荐
梦想的旅途24 小时前
企业微信自动化实战:客户通讯录备份与关系自动迁移
运维·自动化·企业微信
郝学胜_神的一滴5 小时前
Python 高级编程 027:四大推导式全攻略
python·pycharm
菜冻鱼5 小时前
Python-sklearn-特征工程
开发语言·人工智能·python·机器学习·numpy·matplotlib·sklearn
.Peter5 小时前
.NET/WPF 程序在部分 Windows 电脑无法保存用户环境变量:使用 DPAPI 实现安全兼容
windows·信息安全·c#·.net·wpf·环境变量·dpapi
mit6.8245 小时前
archived
后端·python·flask
xian_wwq5 小时前
【学习笔记】Loop Engineering,从手动提示到目标驱动自动化-13/16
笔记·学习·自动化
船长@5 小时前
FastAPI 快速上手:从零基础到实操入门
python·ai·fastapi
码字的特恩5 小时前
微软确认暂不为 Windows 11 加入透明效果自定义功能,建议用户使用第三方工具
人工智能·windows·算法·microsoft·计算机·大模型·编程
我要两颗404西柚5 小时前
2【python】:常用关键字,函数,方法
python
COOLMO研究AI6 小时前
Python 如何给 AI API 实现断路器模式:防止雪崩与保护本地服务
人工智能·python·php