Home > Back-end >  How to replace text in Word document using Openxml
How to replace text in Word document using Openxml

Time:10-11

I have a simple word document with only a single word "$Hello$". I'm trying to change "$Hello$" to "Goodbye" but nothing happens and there's no errors. How can I get the code working? "$Hello$" is in a paragraph.

using System;
using System.IO;
using System.Text.RegularExpressions;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

namespace OpenXMLTests
{
    class Program
    {
        static void Main(string[] args)
        {
            String document = "TestDoc.docx";
            using (WordprocessingDocument doc = WordprocessingDocument.Open(document, true))
            {
                Body body = doc.MainDocumentPart.Document.Body;
                foreach (Table t in body.Descendants<Table>())
                {
                    String tableName = t.GetFirstChild<TableProperties>().TableCaption.Val;
                    Console.WriteLine(tableName);

                }

                string docText = null;  
                using (StreamReader sr = new StreamReader(doc.MainDocumentPart.GetStream()))   //Reads file to string
                {
                    docText = sr.ReadToEnd();
                }
          
                docText = docText.Replace("$Hello$", "Goodbye");

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

            }
        }

    }
}

When I remove this table loop the code works. Not sure whats conflicting

                    Body body = doc.MainDocumentPart.Document.Body;
                    foreach (Table t in body.Descendants<Table>())
                    {
                        String tableName = t.GetFirstChild<TableProperties>().TableCaption.Val;
                        Console.WriteLine(tableName);
    
                    }

CodePudding user response:

Try to disable AutoSave option.

using (WordprocessingDocument doc = 
        WordprocessingDocument.Open(document, true, new OpenSettings { AutoSave = false }))
{
...
}

Looks like when AutoSave is enabled and getter of doc.MainDocumentPart.Document.Body is called it causes that doc.MainDocumentPart is not saved properly or it's overriden with original document part.

  • Related