Search code examples
c#azurems-wordazure-web-app-servicedocx-mailmerge

Mail merge word docx in Azure app service


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();
  }
}

Solution

  • You can give a try using Open XML SDK:

    https://learn.microsoft.com/en-us/office/open-xml/word-processing

    If that doesn't work for some reason, try doing the same using an Azure Logic App:

    https://medium.com/plumsail/create-complex-excel-and-word-documents-from-templates-in-microsoft-flow-azure-logic-apps-and-794334e59f0f