Hi,
public void Test001() throws Exception {
// Prepare data.
ArrayList parents = new ArrayList();
for(int i=0; i<5; i++)
{
Parent parent = new Parent(String.format("Parent_#%d", i));
for(int j=0; j<2; j++)
parent.Children.add(new Child(String.format("Child_#%d_%d", i, j)));
parents.add(parent);
}
// Open tempalte
Document doc = new Document(MyDir + "in.docx");
// Create a datasource.
MailMergeDataSource ds = new MailMergeDataSource(parents, "Parents");
// Execute mail merge with regions.
doc.getMailMerge().executeWithRegions(ds);
// Save output.
doc.save(MyDir + "Out.docx");
}
private static class Parent
{
public Parent(String name)
{
Name = name;
Children = new ArrayList();
}
public final ArrayList Children;
public final String Name;
}
private static class Child
{
public Child(String name)
{
Name = name;
}
public final String Name;
}
class MailMergeDataSource implements IMailMergeDataSource{
public MailMergeDataSource(ArrayList items, String tableName)
{
mItems = items;
mTableName = tableName;
// When the data source is initialized, it must be positioned before the first record.
mRecordIndex= -1;
}
///
/// The name of the data source. Used by Aspose.Words only when executing mail merge with repeatable regions.
///
public String getTableName()
{
return mTableName;
}
///
/// Aspose.Words call this to get a value for every data field.
///
public boolean getValue(String fieldName, Object[] fieldValue)
{
fieldValue[0] = getFieldValue(fieldName);
return fieldValue[0]!=null;
}
public IMailMergeDataSource getChildDataSource(String childName) throws Exception {
Object childData = getFieldValue(childName);
if(childData!=null && ArrayList.class.isInstance(childData))
return new MailMergeDataSource((ArrayList)childData, childName);
return null;
}
///
/// A standard implementation for moving to a next record in a collection.
///
public boolean moveNext()
{
if (isEof())
return false;
mRecordIndex++;
return (!isEof());
}
private boolean isEof()
{
return (mRecordIndex >= mItems.size());
}
private Object getFieldValue(String fieldName)
{
// Get value of the appropriate field usign reflection.
Object item = mItems.get(mRecordIndex);
Class itemClass =item.getClass();
java.lang.reflect.Field field = null;
try{
field = itemClass.getField(fieldName);
} catch(Exception ex){}
if(field!=null)
{
try{
return field.get(item);
} catch(Exception ex){}
return true;
}
return null;
}
private ArrayList mItems;
private int mRecordIndex;
private String mTableName;
}