1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JavaでWord文書を結合する方法

Posted at

はじめに

Word文書を結合することは、複数のWord文書を1つの文書にまとめることができます。この操作により、関連する複数の文書を一元管理し、情報をより簡単に共有することができます。結合する際には、文書全体を挿入する方法や、文書の内容のみをコピーして結合する方法があります。以下に、詳細な手順をご紹介します。

ツール

Jarファイルの導入

  • Free Spire.Doc for Javaをダウンロードして解凍します。
  • IDEAで新しいプロジェクトを作成します。
  • 「File」>「Project Structure」>「Modules」>「Dependencies」をクリックします。
  • 「+」の「JARs or Directories」を選択します。
  • 「Spire.doc.jar」を見つけてプロジェクトにインポートします。

文書全体を挿入する

import com.spire.doc.*;

public class MergeByInserting {
    public static void main(String[] args) {

        //Documentのオブジェクトを作成し、Wordドキュメントを読み込む
        Document document = new Document("sample 1.docx");

        //別のWordドキュメントをこのドキュメントに完全に挿入する
        document.insertTextFromFile("sample 2.docx", FileFormat.Docx_2013);

        //結果ドキュメントを保存する
        document.saveToFile("result 1.docx", FileFormat.Docx_2013);
    }
}

image.png

文書の内容をコピーする

import com.spire.doc.*;

public class MergeByCopying {
    public static void main(String[] args) {

        //2つのDocumentオブジェクトを作成し、2つのWordドキュメントを読み込む
        Document document1 = new Document("sample 1.docx");
        Document document2 = new Document("sample 2.docx");

        //2つ目のドキュメントをループして、すべてのセクションを取得する
        for (Object sectionObj : document2.getSections()) {
            Section sec=(Section)sectionObj;

            //2つ目のドキュメントのセクションをループして、その子オブジェクトを取得する
            for (Object docObj : sec.getBody().getChildObjects()) {
                DocumentObject obj=(DocumentObject)docObj;

                //最初のドキュメントの最後のセクションを取得する
                Section lastSection = document1.getLastSection();

                //最初のドキュメントの最後のセクションに子オブジェクトを追加する
                Body body = lastSection.getBody();
                body.getChildObjects().add(obj.deepClone());
            }
        }

        //結果ドキュメントを保存する
        document1.saveToFile("result 2.docx", FileFormat.Docx_2013);
    }
}

image.png

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?