Wiki
Clone wikiAspose for OpenXML / Search and Replace Text Using OpenXML SDK
Search and Replace Text
Use Range.Replace to find or replace a particular string within the current range. It returns the number of replacements made, so it is useful for searching strings without replace.
Below is code example of search and replace:
Using OpenXML SDK
#!c# using System.IO; using System.Text.RegularExpressions; using DocumentFormat.OpenXml.Packaging; // To search and replace content in a document part. public static void SearchAndReplace(string document) { using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true)) { string docText = null; using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream())) { docText = sr.ReadToEnd(); } Regex regexText = new Regex("Hello world!"); docText = regexText.Replace(docText, "Hi Everyone!"); using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create))) { sw.Write(docText); } } }
Text Manipulation using Aspose SDK
#!c# using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Aspose.Words; namespace TextManipulation { class Program { static void Main(string[] args) { string projectFiles = Path.GetFullPath("../../Files/"); Document doc = new Document(projectFiles + "TestDoc.docx"); // Check the text of the document Console.WriteLine("Original document text: " + doc.Range.Text); // Replace the text in the document. doc.Range.Replace("_CustomerName_", "James Bond", false, false); // Check the replacement was made. Console.WriteLine("Document text after replace: " + doc.Range.Text); // Save the modified document. doc.Save(projectFiles + "ReplaceSimple Out.doc"); System.Console.WriteLine("Press any key to continue"); System.Console.ReadKey(); } } }
Updated