python-docx 库来处理Word文档的页眉和页脚。以下是几种常见的插入页眉和页脚的方法:
pip install python-docx
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Pt, Inches, RGBColor
from datetime import datetime
def add_header_footer_basic(doc_path, output_path):
"""基本示例:添加页眉和页脚"""
# 打开或创建文档
doc = Document()
# 添加一些内容
doc.add_heading('文档标题', 0)
for i in range(5):
doc.add_paragraph(f'这是第 {i+1} 段示例文本。' * 10)
# 获取第一个节的页眉
section = doc.sections[0]
# 1. 添加页眉
header = section.header
header_para = header.paragraphs[0]
header_para.text = "公司机密文档"
header_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 2. 添加页脚
footer = section.footer
footer_para = footer.paragraphs[0]
footer_para.text = f"第 1 页"
footer_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 保存文档
doc.save(output_path)
print(f"文档已保存到: {output_path}")
# 使用示例
add_header_footer_basic('demo.docx', 'output_basic.docx')
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Pt, Inches, RGBColor
from datetime import datetime
def add_formatted_header_footer(doc_path, output_path):
"""添加带格式的页眉和页脚"""
doc = Document()
# 添加文档内容
doc.add_heading('项目报告', 0)
doc.add_paragraph('这是一份详细的项目分析报告。' * 5)
section = doc.sections[0]
# ========== 页眉设置 ==========
header = section.header
# 清除默认段落
header.paragraphs[0].clear()
# 创建表格作为页眉(更灵活布局)
header_table = header.add_table(1, 3, width=Inches(6))
header_table.autofit = False
# 设置列宽
widths = [Inches(2), Inches(2), Inches(2)]
for i, width in enumerate(widths):
header_table.columns[i].width = width
# 添加内容到表格单元格
cells = header_table.rows[0].cells
# 左侧:公司LOGO
left_cell = cells[0]
left_para = left_cell.paragraphs[0]
left_run = left_para.add_run("ACME Corp.")
left_run.bold = True
left_run.font.size = Pt(12)
left_run.font.color.rgb = RGBColor(0, 0, 255) # 蓝色
# 中间:文档标题
center_cell = cells[1]
center_para = center_cell.paragraphs[0]
center_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
center_run = center_para.add_run("项目报告")
center_run.font.size = Pt(14)
center_run.bold = True
# 右侧:日期
right_cell = cells[2]
right_para = right_cell.paragraphs[0]
right_para.alignment = WD_ALIGN_PARAGRAPH.RIGHT
right_run = right_para.add_run(datetime.now().strftime("%Y-%m-%d"))
right_run.italic = True
# ========== 页脚设置 ==========
footer = section.footer
# 清除默认段落
footer.paragraphs[0].clear()
# 创建表格作为页脚
footer_table = footer.add_table(1, 3, width=Inches(6))
# 设置列宽
for i, width in enumerate(widths):
footer_table.columns[i].width = width
footer_cells = footer_table.rows[0].cells
# 左侧:保密级别
footer_left = footer_cells[0].paragraphs[0]
footer_left_run = footer_left.add_run("机密")
footer_left_run.font.color.rgb = RGBColor(255, 0, 0) # 红色
footer_left_run.bold = True
# 中间:页码
footer_center = footer_cells[1].paragraphs[0]
footer_center.alignment = WD_ALIGN_PARAGRAPH.CENTER
footer_center.text = "第 \t 页" # 使用制表符作为页码占位符
# 右侧:公司网址
footer_right = footer_cells[2].paragraphs[0]
footer_right.alignment = WD_ALIGN_PARAGRAPH.RIGHT
footer_right.text = "www.acme.com"
# 添加更多内容测试分页
for i in range(20):
doc.add_paragraph(f"内容段落 {i+1}: " + "这是文档的正文内容。" * 10)
doc.save(output_path)
print(f"文档已保存到: {output_path}")
# 使用示例
add_formatted_header_footer('demo.docx', 'output_formatted.docx')
def add_header_footer_multiple_sections():
"""处理多节文档的页眉页脚"""
doc = Document()
# 第一节
doc.add_heading('第一章', 1)
doc.add_paragraph('这是第一章的内容。' * 20)
# 添加分节符(新节)
doc.add_section()
# 第二节
doc.add_heading('第二章', 1)
doc.add_paragraph('这是第二章的内容。' * 20)
# 为每个节设置不同的页眉页脚
for i, section in enumerate(doc.sections):
# 页眉
header = section.header
header_para = header.paragraphs[0]
header_para.text = f"第 {i+1} 章"
header_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 页脚
footer = section.footer
footer_para = footer.paragraphs[0]
footer_para.text = f"第 {i+1} 章 - 第 \t 页"
footer_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 设置页边距
section.top_margin = Inches(1)
section.bottom_margin = Inches(1)
section.left_margin = Inches(1.25)
section.right_margin = Inches(1.25)
doc.save('output_multisection.docx')
print("多节文档已创建")
# 使用示例
add_header_footer_multiple_sections()
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Pt, Inches, RGBColor
from datetime import datetime
import os
class WordHeaderFooter:
"""Word文档页眉页脚处理类"""
def __init__(self, template_path=None):
"""
初始化
Args:
template_path: 模板文件路径(可选)
"""
if template_path and os.path.exists(template_path):
self.doc = Document(template_path)
else:
self.doc = Document()
def add_content(self, title, paragraphs):
"""添加文档内容"""
self.doc.add_heading(title, 0)
for para in paragraphs:
self.doc.add_paragraph(para)
def set_header(self,
left_text="",
center_text="",
right_text="",
font_size=10,
bold=False,
italic=False):
"""设置页眉"""
section = self.doc.sections[0]
header = section.header
# 清除现有内容
for paragraph in header.paragraphs:
p = paragraph._element
p.getparent().remove(p)
# 添加表格实现三栏布局
table = header.add_table(1, 3, width=Inches(6))
table.style = 'Table Grid'
# 设置列宽
widths = [Inches(2), Inches(2), Inches(2)]
for i, width in enumerate(widths):
table.columns[i].width = width
cells = table.rows[0].cells
# 左侧文本
if left_text:
left_para = cells[0].paragraphs[0]
left_run = left_para.add_run(left_text)
left_run.font.size = Pt(font_size)
left_run.bold = bold
left_run.italic = italic
# 中间文本
if center_text:
center_para = cells[1].paragraphs[0]
center_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
center_run = center_para.add_run(center_text)
center_run.font.size = Pt(font_size)
center_run.bold = bold
center_run.italic = italic
# 右侧文本
if right_text:
right_para = cells[2].paragraphs[0]
right_para.alignment = WD_ALIGN_PARAGRAPH.RIGHT
right_run = right_para.add_run(right_text)
right_run.font.size = Pt(font_size)
right_run.bold = bold
right_run.italic = italic
return self
def set_footer(self,
left_text="",
center_text="",
right_text="",
include_page_number=True,
font_size=9):
"""设置页脚"""
section = self.doc.sections[0]
footer = section.footer
# 清除现有内容
for paragraph in footer.paragraphs:
p = paragraph._element
p.getparent().remove(p)
# 添加表格
table = footer.add_table(1, 3, width=Inches(6))
# 设置列宽
widths = [Inches(2), Inches(2), Inches(2)]
for i, width in enumerate(widths):
table.columns[i].width = width
cells = table.rows[0].cells
# 左侧文本
if left_text:
left_para = cells[0].paragraphs[0]
left_run = left_para.add_run(left_text)
left_run.font.size = Pt(font_size)
# 中间文本(带页码)
center_para = cells[1].paragraphs[0]
center_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
if center_text:
center_run = center_para.add_run(center_text + " ")
center_run.font.size = Pt(font_size)
if include_page_number:
center_para.add_run().add_field('PAGE', '第 { PAGE } 页')
# 右侧文本
if right_text:
right_para = cells[2].paragraphs[0]
right_para.alignment = WD_ALIGN_PARAGRAPH.RIGHT
right_run = right_para.add_run(right_text)
right_run.font.size = Pt(font_size)
return self
def save(self, output_path):
"""保存文档"""
self.doc.save(output_path)
print(f"文档已保存: {output_path}")
return output_path
# 使用示例
def create_report():
"""创建报告文档"""
# 创建文档处理器
word_processor = WordHeaderFooter()
# 添加内容
content = [
"这是报告的引言部分。",
"这是报告的主要内容。",
"这是报告的结论部分。",
]
word_processor.add_content("项目分析报告", content)
# 设置页眉
word_processor.set_header(
left_text="ACME公司",
center_text="项目分析报告",
right_text=datetime.now().strftime("%Y-%m-%d"),
font_size=11,
bold=True
)
# 设置页脚
word_processor.set_footer(
left_text="机密文件",
center_text="",
right_text="版本 1.0",
include_page_number=True,
font_size=9
)
# 保存文档
word_processor.save("项目报告.docx")
# 运行示例
if __name__ == "__main__":
create_report()
# 测试基本功能
print("\n=== 基本功能测试 ===")
add_header_footer_basic('test.docx', 'test_output.docx')
python-docx 的页码字段功能有限,复杂页码格式可能需要使用书签或宏
页眉页脚可见性:页眉页脚只在页面视图中可见,阅读视图中可能不可见
模板文档:可以使用现有的Word模板作为基础
格式继承:页眉页脚的格式独立于正文
如果遇到问题,可以尝试:
# 1. 检查文档是否有节
print(f"文档节数: {len(doc.sections)}")
# 2. 清除已有页眉页脚
section = doc.sections[0]
header = section.header
for paragraph in header.paragraphs:
paragraph.clear()
# 3. 使用不同的对齐方式
from docx.enum.text import WD_ALIGN_PARAGRAPH
paragraph.alignment = WD_ALIGN_PARAGRAPH.LEFT # 左对齐
paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER # 居中对齐
paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT # 右对齐
这些示例展示了如何在Python中使用python-docx库为Word文档添加页眉和页脚。你可以根据需要调整格式和内容。