Insert TableStart/TableEnd in every section

Hi

could you tell me how I can find every section in the document and automatically insert TableStart before the first word and TableEnd after the last word of every section. I have been trying to do it, and it nearly works, but the InsertField does not seem to do it consistently.

I need to do merge using sections within the body of the sections, because they are repeating, but there are fields outside of these, which must be enclosed in the parent tablestart/end. I dont want to have to force the user to understand this extra layer, so would like to add the root table start/end automatically.

Kind regards

Ian Pearce

Hi Ian,

Thanks for your inquiry. Could you please attach your input Word document and expected document here for testing? Please create expected document using MS Word for our reference. We will investigate the issue on our end and provide you code to achieve the same using Aspose.Words.

Best regards,

Hi

please find attached the template and the template we would create.

Just to clarify, we are trying not to have to force the template editor to understand the structure of the tablestart /end tags in the document. They may put other sub tables within here and we use mergeregions always. This works perfectly if the document does not contain sections, and we use code like this:

if (!containsStart)
{
    builder.MoveToDocumentStart();
    builder.InsertField(@"MERGEFIELD TableStart:Letter *MERGEFORMAT");
}

if (!containsEnd)
{
    builder.MoveToDocumentEnd();
    builder.InsertField(@"MERGEFIELD TableEnd:Letter *MERGEFORMAT");
}

but, if there are sections we get a message like:

Mail merge region Letter is badly formed. TableStart and TableEnd should be in the same section, same table row or same table cell.

so I was programmatically hoping to use the documentBuilder to update the template before merging to add in these default root merge table starts and ends.

Kind regards

Ian

Hi Ian,

Thanks for your inquiry. Please try using the following code:

Document doc = new Document(MyDir + @"Sole+Agency+Contract.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
for (int i = 0; i < doc.Sections.Count; i++)
{
    builder.MoveToSection(i);
    builder.InsertField(@"MERGEFIELD TableStart:Letter \*MERGEFORMAT");
    Section sec = doc.Sections[i];
    builder.MoveToParagraph(sec.Body.Paragraphs.Count - 1, 0);
    builder.InsertField(@"MERGEFIELD TableEnd:Letter \*MERGEFORMAT");
}
doc.Save(MyDir + @"15.8.0.docx");

I hope, this helps.

Best regards,

Thanks Awais,

that seems to work perfectly.

Kind regards

Ian