この簡単なチュートリアルでは、Javaを使用してWordドキュメント内のテキストを検索して置換する方法について説明します。単純なAPI呼び出しを使用すると、オペレーティングシステムの環境に関係なく、任意のアプリケーションでJavaを使用してWord文書のテキストを簡単に置き換えることができます。
Javaを使用してWord文書のテキストを置き換える手順
- MavenリポジトリからAspose.Words for JavaJARファイルを構成します
- Document Classインスタンスを作成して、テキストを置き換えるソースドキュメントを開きます
- FindReplaceOptionsクラスを初期化し、検索および置換オプションを設定します
- 検索を実行し、アクティビティをソース文字列とターゲット文字列に置き換えます
- 変更した単語文書をディスクに保存します
- Javaの上記の手順は、いくつかの手順でWord文書を検索して置換します。アクティビティは、 Documentclassオブジェクトを使用してソースDOCXをロードすることから始まります。次に、 FindReplaceOptionsクラス*オブジェクトを作成して、Wordドキュメント内の検索および置換パラメーターを設定します。最後に、選択した基準に基づいて検索と置換のアクティビティを実行し、変更したドキュメントファイルをディスクに保存します。
Javaを使用してWord文書内のテキストを検索および置換するコード
import com.aspose.words.Document; | |
import com.aspose.words.FindReplaceDirection; | |
import com.aspose.words.FindReplaceOptions; | |
import com.aspose.words.License; | |
public class SearchAndReplaceText { | |
public static void main(String[] wordsReplaceArgs) throws Exception { | |
// Apply Aspose.Words for Java license to remove | |
// evaluation version limitations during text replacement | |
License licenseForReplacingTxtInDoc = new License(); | |
licenseForReplacingTxtInDoc.setLicense("Java.Aspose.Words.lic"); | |
// Open the source Word file using Document class | |
Document wordDoc = new Document("Source.docx"); | |
// Initialize FindReplaceOptions class object to replace text string | |
FindReplaceOptions options = new FindReplaceOptions(); | |
options.setMatchCase(true); | |
options.setDirection(FindReplaceDirection.FORWARD); | |
options.setFindWholeWordsOnly(true); | |
// Creating the search and replace string in the Replace method | |
wordDoc.getRange().replace("Sample", "Replace", options); | |
// Save the replaced text result | |
wordDoc.save("FindAndReplace.docx"); | |
} | |
} |
前述のJavaの例では、単純なAPI呼び出しを利用してDOCXの単語を置き換えます。アプリケーションで上記の例を使用するために、MicrosoftWordまたはInteropライブラリに依存していません。 * FindReplaceOptionsクラス*は、一致ケース、置換方向、単語全体の検索など、検索および置換基準を設定するためのさまざまなプロパティを公開します。
このトピックでは、Javaを使用してDOCXでテキストを見つけて置き換えるのがいかに簡単であるかを目撃しました。 Word文書を電子メールとして送信することに興味がある場合は、トピックJavaを使用して電子メールでWord文書を送信する方法で詳細情報を見つけることができます。