@Jon,
您可能需要實現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
}
}