I'm currently making a MailMerge file and want to show a list of strings. In the past I've used a list of objects (for example Customer
) and was able to have something like this in the Word-doc:
{{ #foreach Customers }}
{{Name}}
{{Address}}
{{ /foreach Customers }}
Now however, I have a list of strings
instead of Objects, and I simply want to show them:
{{ #foreach List }}
{{???}}
{{ /foreach List }}
So, what is supposed to go at the ???
. Or should I change the #foreach List
to something like a foreach in .NET C#, i.e. {{ #foreach value in List }}
or something similar?
I haven't been able to find a lot about MailMerge in general to be honest, and nothing about foreach in the MS Word-doc.
If this isn't possible I guess I'll have to put the string in a container-class? Like:
public class StringContainer
{
public string String { get; set; }
}
and
{{ #foreach List }}
{{String}}
{{ /foreach List}}
EDIT:
We use Aspose.Words
(.MailMerge
& .MailMerging
) for this conversion from our Data-object to data in the MS Word doc. Here is the code for the conversion:
private static byte[] GenerateDocument(Stream template, DocumentDataSource dataSource, SaveOptions saveOptions, IFieldMergingCallback fieldMergingCallback = null)
{
var doc = new Document(template);
doc.MailMerge.FieldMergingCallback = fieldMergingCallback;
doc.MailMerge.UseNonMergeFields = true;
doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveContainingFields |
MailMergeCleanupOptions.RemoveUnusedFields |
MailMergeCleanupOptions.RemoveUnusedRegions |
MailMergeCleanupOptions.RemoveEmptyParagraphs;
doc.MailMerge.Execute(dataSource);
doc.MailMerge.ExecuteWithRegions((IMailMergeDataSourceRoot)dataSource);
doc.UpdateFields();
using (var ms = new MemoryStream())
{
doc.Save(ms, saveOptions);
return ms.ToArray();
}
}
And here an example of how we use it:
public byte[] CreateLetter(string filePath, string fileName, OurDataObject data)
{
var path = Path.Combine(filePath, fileName);
using (var fs = File.OpenRead(path))
{
var dataSource = new DocumentDataSource(data);
return GenerateDocument(fs, dataSource, new OoxmlSaveOptions(SaveFormat.Docx));
}
}