当前位置: 代码网 > it编程>编程语言>Java > Java按页、分页符和分节符拆分Word文档的完整指南

Java按页、分页符和分节符拆分Word文档的完整指南

2026年09月18日 Java 我要评论
在文档处理场景中,将一个 word 文件拆分成多个独立文档是一项常见需求。例如,生成单独的章节文件、提取指定页面内容,或将大型报告按结构拆分保存,都需要对原始文档进行精准分割。java 提供了多种方式

在文档处理场景中,将一个 word 文件拆分成多个独立文档是一项常见需求。例如,生成单独的章节文件、提取指定页面内容,或将大型报告按结构拆分保存,都需要对原始文档进行精准分割。

java 提供了多种方式处理 word 文档拆分操作,可以根据不同需求选择合适的拆分依据:按页拆分能够保留文档的页面布局,按分页符拆分适用于人工设置的内容分隔,而按分节符拆分则更适合处理具有章节结构的复杂文档。

本文将介绍如何使用 java 实现 word 文档的按页拆分、按分页符拆分以及按分节符拆分,帮助开发者根据实际业务需求灵活处理 word 文件。

环境设置

要运行下面的代码示例,需要先在 java 项目 中添加 word 文档处理所需的依赖。

如果使用 maven,可以在 ​​pom.xml​​ 中加入:

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.cn/repository/maven-public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupid>e-iceblue</groupid>
        <artifactid>spire.doc</artifactid>
        <version>14.8.4</version>
    </dependency>
</dependencies>

将 word 文档的每一页拆分为单独文件

如果需要按照 word 实际排版后的页面进行拆分,可以使用 ​​document.extractpages()​​ 方法从原文档中提取页面,并生成新的 ​​document​​ 对象。

下面的示例获取 word 文档的总页数,然后逐页提取并保存为独立的 docx 文件:

import com.spire.doc.document;
import com.spire.doc.fileformat;

public class splitwordbypage {
    public static void main(string[] args) {

        // load the word document
        document document = new document();
        document.loadfromfile("sample.docx");

        // get the total number of pages
        int pagecount = document.getpagecount();

        // extract each page to a separate document
        for (int i = 0; i < pagecount; i++) {

            document pagedocument = document.extractpages(i, 1);

            pagedocument.savetofile(
                    "output/page-" + (i + 1) + ".docx",
                    fileformat.docx
            );

            pagedocument.close();
        }

        document.close();
    }
}

例如,一个包含 5 页的 word 文档会被拆分为:

page-1.docx
page-2.docx
page-3.docx
page-4.docx
page-5.docx

​extractpages()​​ 的第一个参数表示起始页面索引,从 ​​0​​ 开始;第二个参数表示需要提取的页面数量。因此:

document.extractpages(i, 1);

表示从索引 ​​i​​ 开始提取 1 页。

提取 word 文档中的指定页码范围

​extractpages()​​ 也可以一次提取连续的多个页面。

例如,需要将原文档的第 3 页到第 6 页保存为一个新的 word 文档,可以使用下面的代码:

import com.spire.doc.document;
import com.spire.doc.fileformat;

public class extractwordpagerange {
    public static void main(string[] args) {

        // load the word document
        document document = new document();
        document.loadfromfile("sample.docx");

        int startpage = 3;
        int endpage = 6;

        // validate the page range
        if (startpage < 1
                || endpage < startpage
                || endpage > document.getpagecount()) {
            throw new illegalargumentexception("invalid page range.");
        }

        // convert the page number to a zero-based index
        int startindex = startpage - 1;

        // calculate the number of pages to extract
        int pagecount = endpage - startpage + 1;

        // extract the specified pages
        document extracteddocument =
                document.extractpages(startindex, pagecount);

        extracteddocument.savetofile(
                "output/pages-3-6.docx",
                fileformat.docx
        );

        extracteddocument.close();
        document.close();
    }
}

需要注意的是,​​extractpages()​​ 使用从 ​​0​​ 开始的页面索引,而且第二个参数是提取页数,不是结束页码。

因此,提取第 3 页到第 6 页时实际调用的是:

document.extractpages(2, 4);

按分页符拆分 word 文档

分页符通常用于强制后续内容从新的一页开始。在 word 中通过 ctrl + enter 插入的分页符属于显式分页符。

如果希望根据这些分页符拆分文档,可以遍历段落中的 ​​break​​ 对象,并通过 ​​breaktype.page_break​​ 判断是否遇到了分页符。

下面的示例在检测到分页符时结束当前文档,并将后续内容写入新的 word 文件:

import com.spire.doc.*;
import com.spire.doc.documents.*;

public class splitwordbypagebreak {

    public static void main(string[] args) {

        // load the source document
        document source = new document();
        source.loadfromfile("sample.docx");

        // create the first output document
        document partdocument = createdocument(source);
        section targetsection = partdocument.getsections().get(0);

        int fileindex = 1;

        // traverse all sections
        for (int s = 0; s < source.getsections().getcount(); s++) {

            section sourcesection = source.getsections().get(s);

            // copy section properties
            sourcesection.clonesectionpropertiesto(targetsection);

            // traverse paragraphs and tables
            for (int i = 0;
                 i < sourcesection.getbody().getchildobjects().getcount();
                 i++) {

                documentobject object =
                        sourcesection.getbody()
                                .getchildobjects()
                                .get(i);

                if (object instanceof table) {

                    targetsection.getbody()
                            .getchildobjects()
                            .add(object.deepclone());

                } else if (object instanceof paragraph) {

                    paragraph paragraph = (paragraph) object;

                    targetsection.getbody()
                            .getchildobjects()
                            .add(paragraph.deepclone());

                    // check for page breaks
                    for (int j = 0;
                         j < paragraph.getchildobjects().getcount();
                         j++) {

                        documentobject child =
                                paragraph.getchildobjects().get(j);

                        if (child instanceof break
                                && ((break) child).getbreaktype()
                                .equals(breaktype.page_break)) {

                            int breakindex =
                                    paragraph.getchildobjects()
                                            .indexof(child);

                            // remove the page break from the current output
                            paragraph outputparagraph =
                                    targetsection.getbody()
                                            .getlastparagraph();

                            outputparagraph.getchildobjects()
                                    .removeat(breakindex);

                            // save the current part
                            partdocument.savetofile(
                                    "output/part-" + fileindex + ".docx",
                                    fileformat.docx
                            );

                            partdocument.close();
                            fileindex++;

                            // create the next document
                            partdocument = createdocument(source);
                            targetsection =
                                    partdocument.getsections().get(0);

                            sourcesection.clonesectionpropertiesto(
                                    targetsection
                            );

                            // copy the paragraph after the page break
                            targetsection.getbody()
                                    .getchildobjects()
                                    .add(paragraph.deepclone());

                            paragraph firstparagraph =
                                    targetsection.getparagraphs().get(0);

                            // remove the page break and content before it
                            while (breakindex >= 0
                                    && firstparagraph.getchildobjects()
                                            .getcount() > 0) {

                                firstparagraph.getchildobjects()
                                        .removeat(breakindex);

                                breakindex--;
                            }

                            if (firstparagraph.getchildobjects()
                                    .getcount() == 0) {

                                targetsection.getbody()
                                        .getchildobjects()
                                        .remove(firstparagraph);
                            }
                        }
                    }
                }
            }
        }

        // save the last part
        partdocument.savetofile(
                "output/part-" + fileindex + ".docx",
                fileformat.docx
        );

        partdocument.close();
        source.close();
    }

    private static document createdocument(document source) {

        document document = new document();

        source.clonedefaultstyleto(document);
        source.clonethemesto(document);
        source.clonecompatibilityto(document);

        document.addsection();

        return document;
    }
}

如果原文档中包含两个分页符,拆分后会得到:

part-1.docx
part-2.docx
part-3.docx

这里识别的是文档中实际存在的 page break。文字因页面空间不足而自动流到下一页并不属于分页符,因此不会触发拆分。

如果需要按照 word 最终显示的每一页拆分文档,应使用前面的 ​​extractpages()​​ 方法。

按分节符拆分 word 文档

word 中的分节符会将文档划分为多个 section。不同 section 可以具有独立的页面尺寸、页边距、页眉页脚和页面方向等设置。

在 spire.doc for java 中,可以直接遍历 ​​document.getsections()​​,将每个 section 克隆到新的 word 文档中。

import com.spire.doc.document;
import com.spire.doc.fileformat;
import com.spire.doc.section;

public class splitwordbysectionbreak {
    public static void main(string[] args) {

        // load the word document
        document document = new document();
        document.loadfromfile("sample.docx");

        // traverse all sections
        for (int i = 0;
             i < document.getsections().getcount();
             i++) {

            section sourcesection =
                    document.getsections().get(i);

            // create a new document
            document sectiondocument = new document();

            // preserve document-level styles and settings
            document.clonedefaultstyleto(sectiondocument);
            document.clonethemesto(sectiondocument);
            document.clonecompatibilityto(sectiondocument);

            // clone the current section
            sectiondocument.getsections()
                    .add(sourcesection.deepclone());

            // save it as a separate word file
            sectiondocument.savetofile(
                    "output/section-" + (i + 1) + ".docx",
                    fileformat.docx
            );

            sectiondocument.close();
        }

        document.close();
    }
}

如果原始文档包含三个 section,拆分后会得到:

section-1.docx
section-2.docx
section-3.docx

一个 section 可以包含一页,也可以包含多页。因此,按分节符拆分并不等同于按页拆分,而是保留每个 section 中包含的全部内容。

word 文档拆分方式对比

拆分方式拆分依据核心实现
每页拆分word 实际页面​extractpages(i, 1)​
指定页码范围连续的实际页面​extractpages(index, count)​
按分页符拆分显式分页符​breaktype.page_break​
按分节符拆分word section​section.deepclone()​

如果需要根据 word 最终排版结果拆分页面,可以使用 ​​extractpages()​​;如果文档已经通过分页符或分节符划分内容,则可以直接按照相应的文档结构进行拆分。

以上就是java按页、分页符和分节符拆分word文档的完整指南的详细内容,更多关于java拆分word的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com