Borrowing some other answers in different places and with the need to overcome four main obstacles:
- Remove any high-level Unicode characters from your replacement string that cannot be read from Word (from incorrect user input).
- Ability to search for a search result across multiple runs or text elements in a paragraph (Word often breaks one sentence into multiple text runs)
- The ability to include line breaks in replacement text to insert multi-line text in a document.
- The ability to pass any node as a starting point for your search, to limit the search to that part of the document (for example, body, title, footer, specific table, table row or TableCell).
I am sure that advanced scripts, such as bookmarks, complex nesting, will need additional modification, but it works on the types of basic text documents that I have used so far and is much more useful for me than ignoring runs in general or using RegEx in the entire file without the ability to target a specific part of TableCell or Document (for advanced scripts).
Usage example:
var body = document.MainDocumentPart.Document.Body; ReplaceText(body, replace, with);
The code:
using System; using System.Collections.Generic; using System.Linq; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; namespace My.Web.Api.OpenXml { public static class WordTools {
Amos zoellner
source share