使用Novacode DocX从word表中删除单元格

时间:2015-06-18 18:15:14

标签: c# docx novacode-docx

如何使用Novacode DocX从单词表中删除单个单元格?

我试过了:

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

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

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

他们都没有移除任何细胞。

4 个答案:

答案 0 :(得分:2)

我最近一直在与Novacode DocX合作。我已经意识到的是,许多方法类都是继承的,并且没有被覆盖。一个示例是cellRemove()继承container,并且永远不会被覆盖以执行您期望它执行的操作。 sorcecode for Novacode.Table

你可以做些什么来试图解决这个问题,就是隐藏细胞/细胞,因为我假设你没有移除整个行或列。

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);

此代码将删除文本并合并第一个表的前两个单元格,并使边框不可见。因此,假设您使用Paragraphs中的Cell文本,这会将您要删除的区域转换为一个不可见的空白单元格。

答案 1 :(得分:0)

您可能需要将表格保存回文档 试试

  1. 将表格附加到文档的末尾。如果那个错过了细胞
  2. 删除并替换文档中的表格。

答案 2 :(得分:0)

您必须自己清除Cell Element中的子XML,因为NovaCode DocX Api无法正确处理它:

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

请注意,最后的InsertParagraph是必需的,因为Cells不能为空。

答案 3 :(得分:0)

Table课程中,您可以使用方法

MergeCells(int, int)

MergeCellsInColumn(int, int, int)

删除&#39;细胞

请参阅:https://docx.codeplex.com/SourceControl/latest#DocX/Table.cs