2

I am trying to create a templating system with OpenXML in our Azure app service-based application (so no Interop) and am running into issues with getting it to work. Here is the code I am currently working with (contents is a byte array):

using(MemoryStream stream = new MemoryStream(contents))
{
    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(stream, true))
    {
        string docText = null;

        using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
        {
            docText = sr.ReadToEnd();
        }

        Regex regexText = new Regex("<< Company.Name >>");
        docText = regexText.Replace(docText, "Company 123");

        using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
        {
            sw.Write(docText);
        }

        wordDoc.Save();
    }

    updated = stream.ToArray();
}

The search text is not being found/replaced, which I am assuming is because of the way everything is stored separately in the XML, but how would I go about replacing a field like this?

Thanks Ryan

rwdial
  • 323
  • 1
  • 4
  • 9
  • My [answer here](https://stackoverflow.com/questions/28697701/openxml-tag-search/28719853#28719853) should help you. – petelids Jan 26 '18 at 12:02

1 Answers1

0

With OpenXML SDK you can use this SearchAndReplace - Youtube, note that it's a screen cast that shows the algorithm that can be used to accomplish the replacement over multiple <w:run> elements.

An alternative approach would be to use pure .NET solution, like this Find and Replace text in a Word document.

Last, the easiest and straightforward approach would be to use some other library, for instance check this example of Find and Replace with GemBox.Document.

Mario Z
  • 4,328
  • 2
  • 24
  • 38
  • Thanks - I wasn't able to get the source from CodeProject due to issues with the site, but found a project on MSDN that worked for me - https://code.msdn.microsoft.com/office/Find-and-Replace-text-in-a-296bf75c/sourcecode?fileId=159173&pathId=1575853171 – rwdial Jan 26 '18 at 16:12