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开始

相关推荐
IvanCodes4 小时前
Python 数据处理(十三):JSON、CSV 与数据序列化
开发语言·python
Patrick在香港5 小时前
Claude 工具调用返回空:8 次失败里只有 1 次状态码不对,其余全带 200
爬虫·python·api·claude·香港
Web3&Basketball5 小时前
CRM Agent 后训练实战:3 倍更少错误
python·架构·大模型·agent·推理
AIFQuant6 小时前
ETF行情API接入踩坑记:从报错到跑通的七个问题
python·金融·区块链·etf·基金
淡海水7 小时前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
GPU实战笔记8 小时前
云端 Python 开发:JupyterLab 还是 VS Code Remote-SSH?
python·vs code·jupyterlab·remote-ssh·远程开发
asdzx678 小时前
如何使用 C# 提取 PPT 文本与图片
c#·ppt·提取文本
狗狗狗狗狗乐啊8 小时前
搭一个 AI 对话工作台 AChat:从 0 到可用的完整记录(一)
python·react.js·ai编程
白猫不黑9 小时前
Python实现简易Web弱口令爆破与防护方案
python·web安全·计算机·网络安全·黑客·信息安全·渗透测试
kuuailetianzi9 小时前
Python初识:定位、优势与发展历程
python