平顶山市转运信息网

使用Python轻松管理Word页脚

2026-03-26 17:07:01 浏览次数:0
详细信息

1. 使用python-docx库(推荐)

基本安装

pip install python-docx

示例代码

from docx import Document

# 1. 添加页脚到新文档
def add_footer_to_new_doc(filename="document_with_footer.docx"):
    """
    创建新文档并添加页脚
    """
    doc = Document()

    # 添加一些内容
    doc.add_heading('带页脚的文档', 0)
    for i in range(5):
        doc.add_paragraph(f'这是第 {i+1} 段内容。' * 10)

    # 获取节(新文档只有一个节)
    section = doc.sections[0]

    # 页脚对象
    footer = section.footer

    # 添加页脚内容
    footer_para = footer.paragraphs[0]
    footer_para.text = "公司机密 - 第 "
    footer_para.add_run("1").bold = True
    footer_para.add_run(" 页")

    # 居中对齐
    footer_para.alignment = 1  # 1=居中对齐

    # 保存文档
    doc.save(filename)
    print(f"已创建文档: {filename}")

# 2. 修改现有文档的页脚
def modify_existing_footer(input_file, output_file):
    """
    修改现有文档的页脚
    """
    doc = Document(input_file)

    for section in doc.sections:
        footer = section.footer

        # 清除原有页脚
        for paragraph in footer.paragraphs:
            paragraph.clear()

        # 添加新页脚
        new_footer = footer.add_paragraph()
        new_footer.text = "修改后的页脚 - "
        run = new_footer.add_run("页码会自动更新")
        run.italic = True
        new_footer.alignment = 2  # 2=右对齐

    doc.save(output_file)
    print(f"已更新页脚: {output_file}")

# 3. 为不同节设置不同页脚
def multiple_sections_footer():
    """
    创建多个节,每个节设置不同的页脚
    """
    doc = Document()

    # 第一节
    doc.add_heading('第一章', 1)
    doc.add_paragraph('第一章内容...')

    # 添加分节符
    doc.add_section()

    # 第二节
    doc.add_heading('第二章', 1)
    doc.add_paragraph('第二章内容...')

    # 为每个节设置不同的页脚
    sections = doc.sections

    # 第一节页脚
    sections[0].footer.paragraphs[0].text = "第一章 - 页眉内容"
    sections[0].footer.paragraphs[0].alignment = 0  # 左对齐

    # 第二节页脚
    sections[1].footer.paragraphs[0].text = "第二章 - 继续阅读"
    sections[1].footer.paragraphs[0].alignment = 2  # 右对齐

    doc.save("multi_section_footer.docx")
    print("已创建多节页脚文档")

# 4. 添加页码
def add_page_number_footer():
    """
    添加页码(静态,需要手动更新)
    """
    doc = Document()

    # 添加内容
    for i in range(10):
        doc.add_paragraph(f'页面 {i+1} 的内容。' * 15)

    # 设置页脚
    section = doc.sections[0]
    footer = section.footer

    # 清除默认段落
    if footer.paragraphs:
        footer.paragraphs[0].clear()
    else:
        footer.add_paragraph()

    # 添加页码
    footer_para = footer.paragraphs[0]
    footer_para.text = "第 "
    footer_para.add_run("{page}").bold = True
    footer_para.add_run(" 页,共 ")
    footer_para.add_run("{numPages}").bold = True
    footer_para.add_run(" 页")
    footer_para.alignment = 1  # 居中对齐

    doc.save("with_page_numbers.docx")
    print("已添加页码")

# 运行示例
if __name__ == "__main__":
    # 示例1:创建带页脚的新文档
    add_footer_to_new_doc()

    # 示例2:如果需要修改现有文档
    # modify_existing_footer("input.docx", "output.docx")

    # 示例3:多节文档
    multiple_sections_footer()

    # 示例4:添加页码
    add_page_number_footer()

2. 高级功能 - 自定义页脚样式

from docx import Document
from docx.shared import Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH

def styled_footer_with_logo():
    """
    创建带样式的页脚,模拟添加logo
    """
    doc = Document()

    # 添加文档内容
    doc.add_heading('公司报告', 0)

    # 获取节
    section = doc.sections[0]
    footer = section.footer

    # 清除默认页脚
    if footer.paragraphs:
        footer.paragraphs[0].clear()

    # 创建表格来布局页脚(模拟左右布局)
    table = footer.add_table(rows=1, cols=3)
    table.autofit = False

    # 设置列宽
    widths = (Pt(100), Pt(300), Pt(100))
    for row in table.rows:
        for idx, cell in enumerate(row.cells):
            cell.width = widths[idx]

    # 左侧单元格:公司信息
    left_cell = table.rows[0].cells[0]
    left_para = left_cell.paragraphs[0]
    left_para.text = "© 2024 公司名称"
    left_para.runs[0].font.size = Pt(9)
    left_para.runs[0].font.color.rgb = RGBColor(128, 128, 128)

    # 中间单元格:页码
    center_cell = table.rows[0].cells[1]
    center_para = center_cell.paragraphs[0]
    center_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
    center_run = center_para.add_run("页码: 1")
    center_run.bold = True
    center_run.font.size = Pt(10)

    # 右侧单元格:文档信息
    right_cell = table.rows[0].cells[2]
    right_para = right_cell.paragraphs[0]
    right_para.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    right_para.text = "机密文档"
    right_para.runs[0].font.size = Pt(9)
    right_para.runs[0].font.color.rgb = RGBColor(255, 0, 0)

    doc.save("styled_footer.docx")
    print("已创建带样式的页脚")

# 运行高级示例
styled_footer_with_logo()

3. 批量处理多个文档

import os
from docx import Document

def batch_update_footers(input_folder, output_folder, footer_text):
    """
    批量更新文件夹中所有Word文档的页脚
    """
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # 遍历文件夹中的所有docx文件
    for filename in os.listdir(input_folder):
        if filename.endswith('.docx'):
            input_path = os.path.join(input_folder, filename)
            output_path = os.path.join(output_folder, filename)

            try:
                doc = Document(input_path)

                # 更新所有节的页脚
                for section in doc.sections:
                    footer = section.footer

                    # 清除旧页脚
                    for paragraph in footer.paragraphs:
                        paragraph.clear()

                    # 添加新页脚
                    new_para = footer.add_paragraph()
                    new_para.text = footer_text
                    new_para.alignment = 1  # 居中对齐

                # 保存文档
                doc.save(output_path)
                print(f"已处理: {filename}")

            except Exception as e:
                print(f"处理 {filename} 时出错: {e}")

# 使用示例
# batch_update_footers("input_docs", "output_docs", "公司统一页脚 - 机密")

4. 实用工具类

class WordFooterManager:
    """
    Word文档页脚管理工具类
    """

    def __init__(self, filepath=None):
        self.doc = Document(filepath) if filepath else Document()
        self.filename = filepath

    def set_footer_text(self, text, alignment='center'):
        """
        设置页脚文本
        alignment: left, center, right
        """
        align_map = {'left': 0, 'center': 1, 'right': 2}

        for section in self.doc.sections:
            footer = section.footer

            # 清除现有内容
            for paragraph in footer.paragraphs:
                paragraph.clear()

            # 添加新内容
            para = footer.add_paragraph(text)
            para.alignment = align_map.get(alignment, 1)

    def set_footer_with_fields(self, left="", center="", right=""):
        """
        设置左右中三个位置的页脚内容
        """
        for section in self.doc.sections:
            footer = section.footer

            # 创建表格布局
            table = footer.add_table(rows=1, cols=3)

            # 设置列宽
            for row in table.rows:
                for i, cell in enumerate(row.cells):
                    if i == 0:
                        cell.width = Pt(100)
                        para = cell.paragraphs[0]
                        para.text = left
                        para.alignment = 0
                    elif i == 1:
                        cell.width = Pt(300)
                        para = cell.paragraphs[0]
                        para.text = center
                        para.alignment = 1
                    else:
                        cell.width = Pt(100)
                        para = cell.paragraphs[0]
                        para.text = right
                        para.alignment = 2

    def save(self, output_path=None):
        """
        保存文档
        """
        save_path = output_path or self.filename
        if not save_path:
            save_path = "output.docx"

        self.doc.save(save_path)
        print(f"文档已保存: {save_path}")
        return save_path

    def add_page_numbers(self, format_str="第 {page} 页"):
        """
        添加页码(静态文本)
        """
        for section_idx, section in enumerate(self.doc.sections):
            footer = section.footer

            # 清除现有内容
            for paragraph in footer.paragraphs:
                paragraph.clear()

            # 添加页码
            para = footer.add_paragraph()
            page_num = section_idx + 1
            para.text = format_str.format(page=page_num)
            para.alignment = 1

# 使用工具类
if __name__ == "__main__":
    # 创建管理器
    manager = WordFooterManager()

    # 添加一些内容
    manager.doc.add_heading("示例文档", 0)
    for i in range(3):
        manager.doc.add_paragraph(f"内容段落 {i+1}")

    # 设置简单页脚
    manager.set_footer_text("公司文档 - 机密", alignment='center')

    # 或者设置三列页脚
    # manager.set_footer_with_fields(
    #     left="版权所有 © 2024",
    #     center="页码",
    #     right="版本 1.0"
    # )

    # 保存文档
    manager.save("managed_footer.docx")

主要功能总结

基础页脚操作:添加、修改、删除页脚 样式控制:字体、颜色、对齐方式 多节支持:不同节使用不同页脚 批量处理:同时更新多个文档 布局控制:使用表格创建复杂布局

注意事项

python-docx 不支持动态页码字段(如自动页码),需要手动设置 如需动态页码,可考虑使用 COM 接口(Windows)或转换为 PDF 处理 处理前建议备份原始文档 对于大型文档,处理可能需要一些时间

这些代码应该能满足您的大部分页脚管理需求。根据具体需求选择合适的方案即可!

相关推荐