Modifying Tables

Is there a way, using DocumentBuilder, to either:

  • add a column to a table
  • delete a column from a table
This is for a document that already has a table in it, and I need to be able to delete/add columns to it.


Aspose.Words object model does not have a concept of columns. To perform this task you should define and delete cells corresponding to a particular column one by one.

Best regards,

I have a table that looks like this:

«head1» «head2» «head3» «head4» «head5» «head6» «head7» «head8»
«TableStart:summary»«col1» «col2» «col3» «col4» «col5» «col6» «col7» «col8»«TableEnd:summary»


I can use the mail merge functionality to fill the table with data, but users can select to have some of the columns hidden (eg., columns, 2 - 7 can be deleted). So I need a way to delete specific columns.

I am currently working out the best way to achieve this. The only solution I’ve come up with so far involves the following function:

private Cell findCellContainingField(Document doc, string fieldname)
{
foreach (Section section in doc.Sections) {
foreach (Table table in section.Body.Tables) {
foreach (Row row in table.Rows) {
foreach (Cell cell in row.Cells) {
foreach (Paragraph paragraph in cell.Paragraphs) {
if (paragraph.Runs.Count <= 2) {
foreach (Run run in paragraph.Runs) {
if (run.Text == " MERGEFIELD " + fieldname + " \* MERGEFORMAT “) {
return cell;
}
}
}
}
}
}
}
}
return null;
}

I can then delete the cell containing the specified merge field.

Is there a better way to locate a cell in a document containing a particular merge field? I tried using a document builder and using docBuilder.MoveToMergeField(“head2”) etc., but there doesn’t then seem to be a way to get the cell object that the builder has moved to.

I don’t like my code above because it relies on the mergefield being in a Run with that specific format (” MERGEFIELD " + fieldname + " \* MERGEFORMAT "). It also means there’s a lot of looping over the document structure.

Are there any better ways to achieve this?


Please try the following code to locate and remove cell containg specified field:

builder.MoveToMergeField("Field1");

Cell cell = builder.CurrentParagraph.GetAncestor(typeof(Aspose.Words.Cell)) as Cell;

if (cell!= null)

cell.Remove();

Note however, that MoveToMergeField method effectively removes the merge field that it moves to. So you should not use this method if you plan to use the specified merge field afterwards.

Best regards,

Thanks a lot, that works a lot better.