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