Mail merge word docx in Azure app service

697 Views Asked by At

In an App Service running on Azure I need to replace mail merge fields in a word/docx-document with content. As I understand interop can't be used because it needs word to be installed.

So how do I replace mail merge fields on Azure in a c# app service? Maybe one can use the OpenXML SDK for this? But how?

[Update] OpenXML worked, I created the following helper class to replace the mailmerge content:

public static void DocXReplaceMergeFields(Stream docStream, Dictionary<string, string> placeholder)
{
  using (var docXml = WordprocessingDocument.Open(docStream, true))
  {
    //docXml.ChangeDocumentType(WordprocessingDocumentType.Document);

    foreach (var run in docXml.MainDocumentPart.Document.Descendants<Run>())
    {
      foreach (var text in run.Descendants<Text>().Where(a => a.Text.StartsWith("«") && a.Text.EndsWith("»")))
      {
        var propertyName = text.Text.Substring(1, text.Text.Length - 2);
        if (placeholder.TryGetValue(propertyName, out var propertyValue))
          text.Text = propertyValue;
      }
    }

    var settingsPart = docXml.MainDocumentPart.GetPartsOfType<DocumentSettingsPart>().First();
    var oxeSettings = settingsPart.Settings.Where(a => a.LocalName == "mailMerge").FirstOrDefault();
    if (oxeSettings != null)
    {
      settingsPart.Settings.RemoveChild(oxeSettings);
      settingsPart.Settings.Save();
    }
    docXml.MainDocumentPart.Document.Save();
  }
}
1

There are 1 best solutions below

3
On BEST ANSWER