Duplicating Word document using OpenXml and C#

前端 未结 6 1795
野趣味
野趣味 2020-12-06 06:27

I am using Word and OpenXml to provide mail merge functionality in a C# ASP.NET web application:

1) A document is uploaded with a number of pre-defined strings for s

6条回答
  •  失恋的感觉
    2020-12-06 06:35

    I second the use of Content Controls recommendation. Using them to mark up the areas of your document where you want to perform substitution is by far the easiest way to do it.

    As for duplicating the document (and retaining the entire document contents, styles and all) it's relatively easy:

    string documentURL = "full URL to your document";
    byte[] docAsArray = File.ReadAllBytes(documentURL);
    
    using (MemoryStream stream = new MemoryStream)
    {
        stream.Write(docAsArray, 0, docAsArray.Length);    // THIS performs doc copy
        using (WordprocessingDocument doc = WordprocessingDocument.Open(stream, true))
        {
            // perform content control substitution here, making sure to call .Save()
            // on any documents Part's changed.
        }
        File.WriteAllBytes("full URL of your new doc to save, including .docx", stream.ToArray());
    }
    

    Actually finding the content controls is a piece of cake using LINQ. The following example finds all the Simple Text content controls (which are typed as SdtRun):

    using (WordprocessingDocument doc = WordprocessingDocument.Open(stream, true))
    {                    
        var mainDocument = doc.MainDocumentPart.Document;
        var contentControls = from sdt in mainDocument.Descendants() select sdt;
    
        foreach (var cc in contentControls)
        {
            // drill down through the containment hierarchy to get to 
            // the contained  object
            cc.SdtContentRun.GetFirstChild().GetFirstChild().Text = "my replacement string";
        }
    }
    

    The and elements may not already exist but creating them is a simple as:

    cc.SdtContentRun.Append(new Run(new Text("my replacement string")));
    

    Hope that helps someone. :D

提交回复
热议问题