Search code examples
c#ms-wordopenxml-sdkword-contentcontrol

Fill word template data using openXML SDK


I have an word file template and xml file for data. I want to find content Content control in word and get data from xml and then replace text in word template. i'm using the following code but it is not updating word file.

using (WordprocessingDocument document = WordprocessingDocument.CreateFromTemplate(txtWordFile.Text))       
{
           MainDocumentPart mainPart = document.MainDocumentPart;
            IEnumerable<SdtBlock> block = mainPart.Document.Body.Descendants<SdtBlock>().Where
                (r => r.SdtProperties.GetFirstChild<Tag>().Val == "TotalClose");
            Text t = block.Descendants<Text>().Single();
             t.Text = "13,450,542";
            mainPart.Document.Save();
}

Solution

  • I think you should write changes to temporary file. See Save modified WordprocessingDocument to new file or my code from work project:

        MemoryStream yourDocStream = new MemoryStream();
        ... // populate yourDocStream with .docx bytes
        using (Package package = Package.Open(yourDocStream, FileMode.Open, FileAccess.ReadWrite))
        {
            //  Load the document XML in the part into an XDocument instance.  
            PackagePart packagePart = LoadXmlPackagePart(package);
            XDocument xDocument = XDocument.Load(XmlReader.Create(packagePart.GetStream()));
    
            // making changes
    
            //  Save the XML into the package  
            using (XmlWriter xw = XmlWriter.Create(packagePart.GetStream(FileMode.Create, FileAccess.Write)))
            {
                xDocument.Save(xw);
            }
    
            var resultDocumentBytes = yourDocStream.ToArray();
        }