yammerade
yammerade

Reputation: 629

Remove cells from word table with Novacode DocX

How do I remove a single cell from a word table using Novacode DocX?

I have tried:

table.Rows[0].Cells.RemoveAt(2);

and

Cell c = table.Rows[0].Cells[2];
table.Rows[0].Cells.Remove(c);

and

table.Rows[0].Cells.RemoveRange(2,4);

None of them remove any cells.

Upvotes: 0

Views: 4705

Answers (4)

Robert
Robert

Reputation: 103

In the Table class you can use the methods

MergeCells(int, int)

and

MergeCellsInColumn(int, int, int)

to 'remove' cells.

See: https://docx.codeplex.com/SourceControl/latest#DocX/Table.cs

Upvotes: 0

Harry Berry
Harry Berry

Reputation: 328

You have to clear the child XML from the Cell Element yourself, as it is not correctly handled by the NovaCode DocX Api:

table.Rows.Last().Cells.Last().Xml.RemoveAll();
table.Rows.Last().Cells.Last().InsertParagraph();

Note that the InsertParagraph in the end is necessary as Cells cannot be empty.

Upvotes: 0

Phillip
Phillip

Reputation: 255

I have been working with Novacode DocX very recently. Something I have realized is that a lot of the methods classes have are inherited and are not overridden. An example is cell inherits Remove() from container and is never overridden to do what you would expect it to do. sorcecode for Novacode.Table

What you can do to try and get around this is to hide the cell/cells, since I am assuming you are not removing an entire row or column.

Novacode.Table table = document.Tables[0]
Novacode.Row row = table.Rows[0]; //int of row that contains cell/cells to remove
int first_cell = 0; //beginning cell of range
int last_cell = 1; //last cell of range
for(int i = first_cell; i < last_cell + 1; i++)
{
    foreach (var paragraph in row.Cells[i].Paragraphs)
    {
        paragraph.Remove(false);
    }
}
row.MergeCells(first_cell, last_cell);
Novacode.Cell cell = row.Cells[first_cell];
Novacode.Border border = new Border();
border.Tcbs = Novacode.BorderStyle.Tcbs_none;
cell.SetBorder(Novacode.TableCellBorderType.Right, border);
cell.SetBorder(Novacode.TableCellBorderType.Left, border);
cell.SetBorder(Novacode.TableCellBorderType.Top, border);
cell.SetBorder(Novacode.TableCellBorderType.Bottom, border);

This code would remove text and merge the first two cells of your first table and make there borders invisible. So this would turn the area you want deleted into one invisible blank cell, assuming you are using Paragraphs of text in the Cell.

Upvotes: 2

MarkKGreenway
MarkKGreenway

Reputation: 8764

You may have to save the table back to the document.
Try

  1. appending the table to the end of the document. if that's missing the cells
  2. Remove and replace the table in the document.

Upvotes: 0

Related Questions