@乔恩,
您可能需要实现 IFieldMergingCallback 接口。事件处理程序“FieldMerging”可用于实现对邮件合并过程的自定义控制。例如,您可以检查传入 MergeField 的值是否为“null”或“空字符串”,然后基于此决定删除父 Cell。这是示例代码:
Document doc = new Document(@"C:\Temp\template.docx");
doc.MailMerge.FieldMergingCallback = new HandleMergeFields();
doc.MailMerge.Execute(new string[] { "a", "b", "c", "d", "e", "f" },
new object[] { "<a>", "<b>", "", "<d>", "<e>", "<f>" });
doc.Save(@"C:\Temp\out.doc");
private class HandleMergeFields : IFieldMergingCallback
{
void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
{
DocumentBuilder builder = new DocumentBuilder(args.Document);
if (string.IsNullOrEmpty(args.FieldValue.ToString()))
{
Field field = args.Field;
Cell cell = field.Start.GetAncestor(NodeType.Cell) as Cell;
// Remove the MergeField
builder.MoveToMergeField(args.FieldName);
//Remove the Cell
cell.Remove();
}
}
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
{
// Do nothing
}
}