我的知识记录

Python Word页眉页脚设置教程

用python-docx给Word文档设置页眉文字、页脚页码、公司Logo,支持首页不同页眉,批量给多个Word文档加上统一的页眉页脚。

场景痛点

公司出的正式文档要求每页都有页眉(公司名+文档名)和页脚(页码+公司地址),几十份文档手动每页加页眉页脚,一份文档点好几次。更烦的是首页不能显示页眉,要单独设置。用python-docx可以批量给所有文档加上统一的页眉页脚,页码自动编号,首页单独控制,一次配置全局生效。

用到的库

pip install python-docx

完整代码

# 导入库
from docx import Document
from docx.shared import Pt, Cm, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn
from docx.oxml import OxmlElement

def set_header(section, header_text):
"""设置页眉文字,居中"""
header = section.header
# 清空默认段落
para = header.paragraphs[0]
para.text = ''
para.alignment = WD_ALIGN_PARAGRAPH.CENTER

run = para.add_run(header_text)
run.font.size = Pt(9)
run.font.name = '微软雅黑'
run._element.rPr.rFonts.set(qn('w:eastAsia'), '微软雅黑')
run.font.color.rgb = RGBColor(128, 128, 128)

def add_page_number(paragraph):
"""在段落中添加页码字段"""
run = paragraph.add_run()
# 插入页码开始标记
fldChar1 = OxmlElement('w:fldChar')
fldChar1.set(qn('w:fldCharType'), 'begin')
# 页码字段指令
instrText = OxmlElement('w:instrText')
instrText.set(qn('xml:space'), 'preserve')
instrText.text = 'PAGE'
# 页码结束标记
fldChar2 = OxmlElement('w:fldChar')
fldChar2.set(qn('w:fldCharType'), 'end')

run._r.append(fldChar1)
run._r.append(instrText)
run._r.append(fldChar2)

def set_footer(section, footer_text):
"""设置页脚:左边文字,右边页码"""
footer = section.footer
para = footer.paragraphs[0]
para.text = ''

# 用制表位实现左右分布
run_left = para.add_run(footer_text)
run_left.font.size = Pt(9)
run_left.font.name = '微软雅黑'
run_left._element.rPr.rFonts.set(qn('w:eastAsia'), '微软雅黑')
run_left.font.color.rgb = RGBColor(128, 128, 128)

# 加一个制表符
run_tab = para.add_run('\t')

# 右边加"第 X 页"
run_label = para.add_run('第 ')
run_label.font.size = Pt(9)
add_page_number(para)
run_end = para.add_run(' 页')
run_end.font.size = Pt(9)

def add_header_footer_to_docx(input_path, output_path,
header_text='宝鸡市稳驰供应链有限公司',
footer_text='地址:宝鸡市金台区 | 电话:0917-1234567'):
"""给单个Word文档添加页眉页脚"""
doc = Document(input_path)

# 文档可能有多个section,全部设置
for section in doc.sections:
set_header(section, header_text)
set_footer(section, footer_text)

# 首页不显示页眉页脚(取消注释可开启)
# for section in doc.sections:
#     section.different_first_page_header_footer = True

doc.save(output_path)
print(f'页眉页脚已添加:{output_path}')

if __name__ == '__main__':
add_header_footer_to_docx(
input_path='demo.docx',
output_path='带页眉页脚.docx'
)

代码讲解

  • doc.sections返回文档的节(section),每个节有自己的页眉页脚设置。一个文档默认一个节,分节文档会有多个,遍历全部节才能确保每页都生效。
  • section.header.paragraphs[0]拿到页眉的第一个段落,直接写入文字。页脚同理用section.footer
  • 页码不是普通文字,是Word字段(field),需要通过XML层插入PAGE字段指令。代码里用OxmlElement构造三个XML元素:begin标记、PAGE指令、end标记,拼到run的XML里。打开文档后Word会自动渲染成当前页码。
  • 页脚用\t制表符把文字和页码分开,实现左边公司信息右边页码的排版效果。
  • different_first_page_header_footer = True可以让首页使用单独的页眉页脚,做封面时很有用。

运行结果

运行脚本后生成带页眉页脚.docx,打开可以看到每页顶部居中灰色小字公司名,每页底部左侧公司地址电话,右侧自动显示"第 X 页",翻到第二页页码自动变成2。

注意事项

  • 页码字段在Word里打开会自动计算,但用python-docx本身读不到页码值,因为那是Word渲染时算出来的。
  • 页眉页脚里的文字同样需要设置eastAsia中文字体,否则中文可能显示不对。
  • 如果文档原本就有页眉页脚,直接往paragraphs[0]写会覆盖原内容,需要先清空。
  • 不同节的页眉页脚默认是链接到前一节的,改第一个节其他节会跟着变,这是正常行为。

Python Word页眉页脚设置教程

标签:

更新时间:2026-09-14 21:48:21

上一篇:Python Word添加标题样式多级目录教程

下一篇: