You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python docxcompose合并Word文档如何保留各文档不同页眉

问题原因

你当前的配置没有生效,核心原因是你修改的是待合并的源子文档对象的section属性,这个属性不会被同步到合并后的主文档的对应section中。docxcompose合并文档时默认会让新增section的页眉链接到前一节,直接继承前一节的页眉内容,就会出现所有页眉都和首个文档一致的问题。

解决方法

核心逻辑:每追加一个子文档到主文档后,立刻定位主文档中刚新增的对应section,将该section的页眉设置为不链接到前一节,即可保留源子文档的独立页眉。

修改后可运行代码
import os
from docx import Document
from docxcompose.composer import Composer

def mergeDocToOne(self, seperatepath, megerpathAndFileName):
    original_docx_path = seperatepath
    new_docx_path = megerpathAndFileName

    all_word = os.listdir(original_docx_path)
    all_file_path = []
    for file_name in all_word:
        # 过滤有效docx文件,排除临时缓存文件
        if file_name.endswith('.docx') and not file_name.startswith('~$'):
            all_file_path.append(os.path.join(original_docx_path, file_name))
    
    if not all_file_path:
        return
    
    # 初始化主文档
    master = Document(all_file_path[0])
    composer = Composer(master)

    # 遍历追加剩余文档
    for word_path in all_file_path[1:]:
        sub_doc = Document(word_path)
        # 记录追加前主文档的section数量
        pre_section_num = len(composer.doc.sections)
        # 追加子文档,开启页眉页脚导入
        composer.append(sub_doc, import_headers_footers=True)
        # 定位追加后新增的section(单页子文档默认对应1个section)
        new_section = composer.doc.sections[pre_section_num]
        # 断开页眉和前一节的链接,保留当前文档独立页眉
        new_section.header.is_linked_to_previous = False

        # 如有以下需求可取消对应注释:
        # 1. 保留首页不同的页眉
        # new_section.header.first_page.is_linked_to_previous = False
        # 2. 保留偶数页独立页眉
        # new_section.header.even_page.is_linked_to_previous = False
        # 3. 保留独立页脚
        # new_section.footer.is_linked_to_previous = False
    
    composer.save(new_docx_path)
注意事项

如果你的子文档是多页、且存在多个section的情况,需要把新增的所有section都遍历设置一次is_linked_to_previous = False即可。

内容的提问来源于stack exchange,提问作者Jeffrey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 09:36:04