Free Support Forum - aspose.com

Programmatically delete a table from a template

Hi,

I have a table in my template that I want to delete if there is no data in the DB to populate the table.

I tried an approach of wrapping the table in a bookmark and then trying various options such as:

- going to bookmark and removing current paragraph
- going to bookmark and setting current paragraph to empty string

The above just deletes the first few words from the first heading.

Any tips?

Thanks,
Will

Hi<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your request you can remove table from document using the following code for example.

Document doc = new Document(@"Test033\in.doc");

doc.FirstSection.Body.Tables[0].Remove();

Also you can attach your document and I will try to help you.

Best regards.

Thank you very much. That worked fine.

Is there a slightly more robust way to do it then depending on the table being the first table in the section?

Our goal is to allow business users a decent amount of flexibility in modifying templates. If they move the order of the tables or move them to different sections, it breaks code.

I have the section problem figured out by putting a bookmark on the table to delete and then going to that bookmark to find the right section. However, this doesn’t handle the case where tables may be re-ordered.

Thanks for the quick reply,
Will

Hi<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your request. You can insert bookmark into one cell of table and use the following code to remove this table.

Document doc = new Document(@"Test102\in.doc");

//Get bookmark inserted into the table cell

Bookmark tableBookmark = doc.Range.Bookmarks["table1"];

//Remove table.

//First ParentNode is Paragraph

//Second ParentNode is Cell

//Third - Row

//Forth - Table

tableBookmark.BookmarkStart.ParentNode.ParentNode.ParentNode.ParentNode.Remove();

//Save output document

doc.Save(@"Test102\out.doc");

Also you can insert bookmark in paragraph directly above the table. Then you should use the following code.

Document doc = new Document(@"Test102\in.doc");

//Get bookmark inserted into the table cell

Bookmark tableBookmark = doc.Range.Bookmarks["table2"];

//GEt parent paregraph

Node parentParagraph = tableBookmark.BookmarkStart.ParentNode;

//If next node is Tabble then remove it

if (parentParagraph.NextSibling.NodeType == NodeType.Table)

{

parentParagraph.NextSibling.Remove();

}

//Save output document

doc.Save(@"Test102\out.doc");

I hope this could help you.

Best regards.