Spire.doc 合并word,复制word

发布于:2024-12-08 ⋅ 阅读:(140) ⋅ 点赞:(0)

之前使用的poi来实现这个功能,然后发现在复制chart时,边框样式无法修改,于是就使用了spire.doc

1. 引入依赖

    <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.free</artifactId>
            <version>5.2.0</version>
        </dependency>
        
    </dependencies>

2. 如果只是合并文档,可以使用spire.doc 自带的合并方法

    public static void main(String[] args) {
        Document doc = new Document("test.docx");
        doc.insertTextFromFile("append.docx", FileFormat.Docx);
        doc.saveToFile("out.docx", FileFormat.Docx);
    }

这个方法有个弊端,就是两个文档中间会自动分节,如果对格式有要求的话,建议用下面的方法

3. 使用复制元素的方法来追加文档内容

    public static void appendDoc(Document srcDoc, Document appendDoc) {
        SectionCollection sections = appendDoc.getSections();
        for (Section section : (Iterable<Section>) sections) {
            for (int j = 0; j < section.getBody().getChildObjects().getCount(); j++) {
                //获取文档中的段落和表格
                DocumentObject obj = section.getBody().getChildObjects().get(j);
                //将文档中的段落和表格插入到新的文档中
                srcDoc.getLastSection().getBody().getChildObjects().add(obj.deepClone());
            }
        }
    }

核心思想是从目标文档的最后一节开始追加源文档的每个元素,这个方法对文档格式没有任何影响,只是单纯的追加内容,如果中间需要加空行或者其他要素,需要修改上面的方法


网站公告

今日签到

点亮在社区的每一天
去签到