The sample code and explanation provided in the documentation does not work for editing Word Document. It leaves the document in unreadable and incorrect format and the file does not open in MS Word.
The below sample code provided on StackOverflow, although inefficient, seems to work with some catches.
using ( WordprocessingDocument doc =
WordprocessingDocument.Open(@"yourpath\testdocument.docx", true))
{
var body = doc.MainDocumentPart.Document.Body;
var paras = body.Elements<Paragraph>();
foreach (var para in paras)
{
foreach (var run in para.Elements<Run>())
{
foreach (var text in run.Elements<Text>())
{
if (text.Text.Contains("text-to-replace"))
{
text.Text = text.Text.Replace("text-to-replace", "replaced-text");
}
}
}
}
}
}
The sample code and explanation provided in the documentation does not work for editing Word Document. It leaves the document in unreadable and incorrect format and the file does not open in MS Word.
The below sample code provided on StackOverflow, although inefficient, seems to work with some catches.