Remove cells from word table with Novacode DocX

4.6k views Asked by At

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.

4

There are 4 answers

1
MarkKGreenway On

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.
0
Harry Berry On

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.

0
Phillip On

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.

0
Robert On

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