How to insert text into a content control using the Open XML SDK

I am trying to develop a solution that takes input from an ASP.Net web page and embeds the input values ​​in the appropriate content controls in an MS Word document. An MS Word document also has static data with some dynamic data to insert into the header and footer fields.

The idea here is that the solution should be web based. Can I use OpenXML for this purpose or any other approach you can offer.

Thank you for all your valuable materials. I really appreciate them.

+4
source share
1 answer

, , Word:

public static WordprocessingDocument InsertText(this WordprocessingDocument doc, string contentControlTag, string text)
{
    SdtElement element = doc.MainDocumentPart.Document.Body.Descendants<SdtElement>()
      .FirstOrDefault(sdt => sdt.SdtProperties.GetFirstChild<Tag>()?.Val == contentControlTag);

    if (element == null)
      throw new ArgumentException($"ContentControlTag \"{contentControlTag}\" doesn't exist.");

    element.Descendants<Text>().First().Text = text;
    element.Descendants<Text>().Skip(1).ToList().ForEach(t => t.Remove());

    return doc;
}

- Tag ( , ) , . - , . , , , :

internal static WordprocessingDocument RemoveSdtBlocks(this WordprocessingDocument doc, IEnumerable<string> contentBlocks)
{
    List<SdtElement> SdtBlocks = doc.MainDocumentPart.Document.Descendants<SdtElement>().ToList();

    if (contentBlocks == null)
        return doc;

    foreach(var s in contentBlocks)
    {
        SdtElement currentElement = SdtBlocks.FirstOrDefault(sdt => sdt.SdtProperties.GetFirstChild<Tag>()?.Val == s);
        if (currentElement == null)
            continue;
        IEnumerable<OpenXmlElement> elements = null;

        if (currentElement is SdtBlock)
            elements = (currentElement as SdtBlock).SdtContentBlock.Elements();
        else if (currentElement is SdtCell)
            elements = (currentElement as SdtCell).SdtContentCell.Elements();
        else if (currentElement is SdtRun)
            elements = (currentElement as SdtRun).SdtContentRun.Elements();

        foreach (var el in elements)
            currentElement.InsertBeforeSelf(el.CloneNode(true));
        currentElement.Remove();
    }
    return doc;
}

WordProcessingDocument , .

:

/ memystream, , , :

byte[] byteArray = File.ReadAllBytes(@"C:\...\Template.dotx");

using (var stream = new MemoryStream())
{
    stream.Write(byteArray, 0, byteArray.Length);

    using (WordprocessingDocument doc = WordprocessingDocument.Open(stream, true))
    {
       //Needed because I'm working with template dotx file, 
       //remove this if the template is a normal docx. 
        doc.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
        doc.InsertText("contentControlName","testtesttesttest");
    }
    using (FileStream fs = new FileStream(@"C:\...\newFile.docx", FileMode.Create))
    {
       stream.WriteTo(fs);
    }
}
+5

All Articles