How to Replace Text in a Word Document

This article was translated from English: Does it need improvement?
Translated
View the article in English

Automating text replacement in Word documents is a common need, whether you're personalizing templates, updating reports, or managing content in bulk. IronWord is a C# library designed to make this task straightforward and efficient.

A key advantage of IronWord is that it manipulates Word documents directly, without relying on Microsoft Office Interop. This means you don't need Word installed on your server, resulting in a significantly faster, more reliable, and scalable solution for back-end processes and web applications.

In this how-to guide, we'll walk through code examples to show you just how easily you can find and replace text in any Word document.

Quickstart: Replace Text in Word Documents Easily

This quick guide demonstrates how to swiftly replace text in a Word document using IronWord. With just a few lines of C#, you can load a DOCX file, replace specified text, and save the updated document. This efficient process ensures that developers can enhance document automation without the need for Microsoft Office Interop, making it ideal for backend processes and web applications.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronWord with NuGet Package Manager

    PM > Install-Package IronWord

  2. Copy and run this code snippet.

    IronWord.Document doc = new IronWord.Document("sample.docx");
    doc.ReplaceText("oldText", "newText");
    doc.SaveAs("updated.docx");
  3. Deploy to test on your live environment

    Start using IronWord in your project today with a free trial
    arrow pointer

Replace Text Example

Replacing text within a Word Document is intuitive with IronWord. First, we load an existing document. Then, we access the paragraphs collection through Paragraphs and use the ReplaceText method on a specific paragraph.

The ReplaceText method takes two string parameters: the text to find and the text to replace it with.

Conseils The ReplaceText method is case-sensitive and replaces all instances of the string within the selected paragraph.

ConseilsAll object lists used in this example follow zero-based indexing.

Input

In this example, we'll be using this sample Word document that contains two paragraphs, both with the text "old text".

Sample Docx

Code

Here's the code below, we'll be replacing the first paragraph of "old text" with the word "new text".

:path=/static-assets/word/content-code-examples/how-to/replace-words.cs
using IronWord;

// Open existing Word
WordDocument doc = new WordDocument("sample.docx");

// Replace the first paragraph's old text with new text
doc.Paragraphs[0].ReplaceText("old text", "new text");

// Save updated Word Document
doc.SaveAs("updated.docx");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output

Output Docx

As you can see in the output file, only the first paragraph's text has been changed, while the second remains untouched.

Replacing Multiple Text

To replace every occurrence of a word throughout the entire document, loop through theParagraphscollection and apply theReplaceTextmethod to each one.

We'll use the same sample.docx file as before. If the text to be replaced isn't found in a paragraph, no operation is performed, and the loop continues to the following paragraph.

Veuillez noter If the text you wish to replace is not found, no operations will be performed.

Code

Here's the code below, we'll be replacing the first paragraph of "old text" with the word "new text".

:path=/static-assets/word/content-code-examples/how-to/replace-words-multiple.cs
using IronWord;

// Open existing Word
WordDocument doc = new WordDocument("sample.docx");

// Loop through each paragraph to find and replace text
for (int i = 0; i < doc.Paragraphs.Count; i++)
{
    // Replace all occurrences of "old text" with "new text" in the current paragraph
    doc.Paragraphs[i].ReplaceText("old text", "new text");
}

// Save updated Word Document
doc.SaveAs("updated.docx");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output

Output Multiple Docx

As you can see from this updated Word Document, both paragraphs have been replaced with the word "new text".

Find Text

If you need to verify that text exists before performing an operation, you can use the FindText method. This method searches the entire document and returns the first TextElement that matches the search query.

Below is an example of searching for the old text in the Word document mentioned above.

Code

:path=/static-assets/word/content-code-examples/how-to/replace-words-find-text.cs
using IronWord;
using System;

// Open existing Word
WordDocument doc = new WordDocument("sample.docx");

// Returns the first TextContent element that contains the specified text.
Console.WriteLine(doc.FindText("old text"));
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output

Find Text Output

As you can see, it returned the matching text.

Avertissement If FindText returns nothing, the text does not exist in the document. Ensure your search term is spelled correctly and matches the case of the text in the document.

Questions Fréquemment Posées

À quoi sert IronWord ?

IronWord est une bibliothèque C# utilisée pour automatiser le remplacement de texte dans les documents Word. Elle simplifie des tâches telles que la personnalisation des modèles, la mise à jour des rapports et la gestion de contenu en vrac.

Ai-je besoin de Microsoft Word installé pour utiliser IronWord ?

Non, IronWord ne repose pas sur Microsoft Office Interop, vous n'avez donc pas besoin de Word installé sur votre serveur. Cela en fait une solution plus rapide et plus évolutive pour manipuler des documents Word.

Comment remplacer le texte dans un document Word en utilisant IronWord ?

Pour remplacer le texte dans un document Word en utilisant IronWord, chargez le document, accédez aux paragraphes et utilisez la méthode ReplaceText pour substituer l'ancien texte par le nouveau texte.

La méthode ReplaceText dans IronWord est-elle sensible à la casse ?

Oui, la méthode ReplaceText dans IronWord est sensible à la casse et remplace toutes les occurrences de la chaîne spécifiée dans le paragraphe sélectionné.

Puis-je remplacer du texte dans l'ensemble du document avec IronWord ?

Oui, vous pouvez remplacer le texte dans l'ensemble du document en parcourant la collection Paragraphs et en appliquant la méthode ReplaceText à chaque paragraphe.

Que se passe-t-il si le texte à remplacer n'est pas trouvé dans un paragraphe ?

Si le texte n'est pas trouvé dans un paragraphe, aucune opération n'est effectuée et la boucle passe au paragraphe suivant.

Comment puis-je vérifier si un texte spécifique existe dans un document en utilisant IronWord ?

Vous pouvez utiliser la méthode FindText pour rechercher dans l'ensemble du document et renvoyer le premier TextElement qui correspond à la requête de recherche.

Que dois-je faire si FindText ne retourne rien ?

Si FindText ne retourne rien, cela signifie que le texte n'existe pas dans le document. Assurez-vous que votre terme de recherche est orthographié correctement et qu'il correspond à la casse du texte dans le document.

Curtis Chau
Rédacteur technique

Curtis Chau détient un baccalauréat en informatique (Université de Carleton) et se spécialise dans le développement front-end avec expertise en Node.js, TypeScript, JavaScript et React. Passionné par la création d'interfaces utilisateur intuitives et esthétiquement plaisantes, Curtis aime travailler avec des frameworks modernes ...

Lire la suite
Prêt à commencer?
Nuget Téléchargements 25,807 | Version : 2025.11 vient de sortir