Java如何实现合并word文档

在做项目中,遇到了一种情况,需要将一个小word文档的内容插入到一个大word(主文档)中。

实现

1.首先定义好主文档

在主文档需要插入小word文档的位置上添加一个书签,这个书签名字要记住,后面要用。

2.定义需要追加的文档

3. 代码实现

 

package com.example.filedemo.controller;

import com.aspose.words.Body;
import com.aspose.words.Bookmark;
import com.aspose.words.BookmarkCollection;
import com.aspose.words.CompositeNode;
import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.ImportFormatMode;
import com.aspose.words.Node;
import com.aspose.words.NodeImporter;
import com.aspose.words.Orientation;
import com.aspose.words.PaperSize;
import com.aspose.words.Section;

public class Test1 {
    public static void main(String[] args) {
        try {
            //主文档
            Document mainDocument = new Document("C:\\Users\\admin\\Desktop\\qq.docx");
            //需要进行追加的文档
            Document file1 = new Document("C:\\Users\\admin\\Desktop\\科技依据.docx");
            Document file11 = new Document("C:\\Users\\admin\\Desktop\\研究方法和技术路线.docx");
            Document file2 = new Document("C:\\Users\\admin\\Desktop\\内容和预期成果.docx");
            Document file3 = new Document("C:\\Users\\admin\\Desktop\\研究方法和技术路线.docx");
            //第四个参数是书签名,需要和步骤1在大word文档中定义的书签名对上
            appendDocument(mainDocument, file1, true, "shuqian1");
            appendDocument(mainDocument, file11, true, "shuqian1");
            appendDocument(mainDocument, file2, true, "shuqian2");
            appendDocument(mainDocument, file3, true, "shuqian3");
            System.out.println("成功!");
            //将最终合并完成后的文档对象保存到文件中
            mainDocument.save("C:\\Users\\admin\\Desktop\\qq1.docx");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param mainDoc    主文档
     * @param addDoc     要拼接的文档
     * @param isPortrait 是否横向拼接
     * @param bookmark   书签名称,将add文档拼接到主文档哪个位置
     * @Description 文档拼接
     */
    public static void appendDocument(Document mainDoc, Document addDoc, boolean isPortrait, String bookmark) {
        DocumentBuilder builder = null;
        try {
            builder = new DocumentBuilder(mainDoc);
            BookmarkCollection bms = mainDoc.getRange().getBookmarks();
            Bookmark bm = bms.get(bookmark);
            if (bm != null) {
                builder.moveToBookmark(bookmark, true, false);
                builder.writeln();
                builder.getPageSetup().setPaperSize(PaperSize.A4);
                if (isPortrait) {
                    builder.getPageSetup().setOrientation(Orientation.PORTRAIT);
                } else {
                    builder.getPageSetup().setOrientation(Orientation.LANDSCAPE);
                }
                Node insertAfterNode = builder.getCurrentParagraph().getPreviousSibling();
                insertDocumentAfterNode(insertAfterNode, mainDoc, addDoc);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param insertAfterNode 插入的位置
     * @param mainDoc         主文档
     * @param srcDoc          要拼接进去的文档
     * @Description
     * @Return void
     */
    @SuppressWarnings("rawtypes")
    private static void insertDocumentAfterNode(Node insertAfterNode, Document mainDoc, Document srcDoc) throws Exception {
        if (insertAfterNode.getNodeType() != 8 && insertAfterNode.getNodeType() != 5) {
            throw new Exception("The destination node should be either a paragraph or table.");
        } else {
            CompositeNode dstStory = insertAfterNode.getParentNode();
            Body body = srcDoc.getLastSection().getBody();
            while (null != body.getLastParagraph() && !body.getLastParagraph().hasChildNodes()) {
                srcDoc.getLastSection().getBody().getLastParagraph().remove();
            }

            NodeImporter importer = new NodeImporter(srcDoc, mainDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING);
            int sectCount = srcDoc.getSections().getCount();

            for (int sectIndex = 0; sectIndex < sectCount; ++sectIndex) {
                Section srcSection = srcDoc.getSections().get(sectIndex);
                int nodeCount = srcSection.getBody().getChildNodes().getCount();
                for (int nodeIndex = 0; nodeIndex < nodeCount; ++nodeIndex) {
                    Node srcNode = srcSection.getBody().getChildNodes().get(nodeIndex);
                    Node newNode = importer.importNode(srcNode, true);
                    dstStory.insertAfter(newNode, insertAfterNode);
                    insertAfterNode = newNode;
                }
            }
        }
    }
}

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值