0
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ドキュメント内のテキストを置換する方法

Last updated at Posted at 2022-07-19

Word ドキュメント内のテキストを置換する必要がある場合があります。例えば、ドキュメント内で誰かの名前のスペルを何度も間違えてしまい、正しい名前に更新する必要がある場合や、テンプレートからWordドキュメントを生成する際に、プレースホルダーのテキストを置き換える必要がある場合などです。この操作を自動化するために、この記事では、Free Spire.Doc for Javaライブラリを使用してWordドキュメント内のテキストを置換する方法について説明します。この記事では、以下のトピックを扱います。

【依存関係の追加】

この方法は、無償のFree Spire.Doc for Javaが必要ですので、先にjarファイルをインポートしてください。

1. Maven

Maven を使用している場合、プロジェクトの pom.xml ファイルに以下のコードを追加することで、簡単にアプリケーションに JAR ファイルをインポートすることができます。

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc.free</artifactId>
        <version>5.2.0</version>
    </dependency>
</dependencies>

2. 公式サイトよりJarファイルをダウンロード

まず、Free Spire.Doc for Java の公式サイトよりzipファイルをダウンロードします。zipファイルを解凍し、libフォルダの下にあるSpire.Doc.jarファイルを依存関係としてプロジェクトにインポートしてください。

ドキュメント内のテキストの置換

Free Spire.Doc for Javaは、Wordドキュメントを表す Document クラスを提供します。このクラスには、開発者がドキュメント内のテキストを置換できるようにする置換方法が含まれています。

次のコード例では、Javaを使用してWord文書内のテキストを置換する方法を説明します。

import com.spire.doc.Document;
import com.spire.doc.FileFormat;

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

        //Wordドキュメントを読み込む
        Document document = new Document("テンプレート.docx");

        //指定のテキストを置き換える
        document.replace("Java", "JavaScript", false, true);

        //結果のドキュメントを保存する
        document.saveToFile("ドキュメント内のテキス7トの置換.docx", FileFormat.Docx);
    }
}

2022-07-18_155306.png

表内のテキストの置換

上記の例では、ドキュメント内の検出されたテキストをすべて置換しています。指定した表のテキストだけを置換する場合は、 Table クラスの置換する方法を使用します。

次のコード例では、Java を使用して Word ドキュメント内の表内のテキストを置換する方法を説明します。

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.Table;
import java.util.HashMap;
import java.util.Map;

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

        //Wordドキュメントを読み込む
        Document document = new Document("C:/Users/Allen/Desktop/New Microsoft Word Document (2).docx");

        //最初のセクションを取得する
        Section section = document.getSections().get(0);

        //セクション内の最初のテーブルを取得する
        Table table = section.getTables().get(0);

        //値のマッピングを作成する
        Map<String, String> map = new HashMap();
        map.put("@氏名","伊藤  つかさ");
        map.put("@年齢","28");
        map.put("@電話番号","090-5986-4568");
        map.put("@部門","営業部");
        map.put("@メールアドレス","itotsukasa@gmail.com");

        //表中のテキストを置換する
        for (Map.Entry<String, String> entry : map.entrySet()) {
            table.replace(entry.getKey(), entry.getValue(), false, true);
        }

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

2022-07-18_173749.png

テキストを画像に置き換える

実は、Free Spire.Doc for Javaでは、テキストを画像に置き換える直接的な方法は提供されていません。この操作は、テキストのインデックス位置を求め、その位置に画像を挿入し、その後、ドキュメントからテキストを削除することで実現できます。

次のコード例は、Javaを使用してWordドキュメント内のテキストを画像に置き換える方法を説明するものです。

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;

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

        //Wordドキュメントを読み込む
        Document document = new Document("C:/Users/Allen/Desktop/New Microsoft Word Document (2).docx");

        //テキストを検索する
        TextSelection textSelection = document.findString("@写真", false, true);

        //画像を読み込む
        DocPicture pic = new DocPicture(document);
        pic.loadImage("C:/Users/Allen/Desktop/写真.png");

        //画像の高さと幅を設定する
        pic.setHeight(128);
        pic.setWidth(128);

        //テキストのインデックス位置を取得する
        TextRange range =  textSelection.getAsOneRange();
        int index = range.getOwnerParagraph().getChildObjects().indexOf(range);

        //この位置に画像を挿入する
        range.getOwnerParagraph().getChildObjects().insert(index,pic);

        //このテキストを削除する
        range.getOwnerParagraph().getChildObjects().remove(range);

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

2022-07-19_110928.png

正規表現によるテキストの置換

正規表現は、正規表現エンジンが入力テキストで一致させようとするパターンです。テキストを処理するための強力で柔軟、かつ効率的な方法を提供します。

次のコード例では、Javaを使用してWordのテキストを正規表現で置き換える方法を説明します。

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import java.util.regex.Pattern;

public class ReplaceTextByRegEx {
    public static void main(String []args){
        //Wordドキュメントを読み込む
        Document doc = new Document();
        doc.loadFromFile("C:/Users/Allen/Desktop/New Microsoft Word Document.docx");

        //括弧内のテキストを置換するRegExを作成する
        Pattern regex=Pattern.compile("(?<=\\()[^\\)]+");

        //regexでテキストを置き換える
        doc.replace(regex,"ジャバスクリプト");

        //ドキュメントを保存する
        doc.saveToFile("ReplaceTextByRegex.docx", FileFormat.Docx_2013);
    }
}

2022-07-19_103807.png

【結語】

本記事では、Wordドキュメント内のテキストを置換する方法をいくつか紹介しました。説明した方法以外にも、Free Spire.Doc for Javaライブラリを使用して、Wordドキュメント内のテキストを置換したり、HTML内のテキストを置換したり、テーブル内のテキストを置換したりすることも可能です。しかし、私はそれを制限内に保つために、ここで記事を終了しています。ご興味のある方は、ご自身で試してみてください。

0
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
0
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?