【问题标题】:Remove cells from word table with Novacode DocX使用 Novacode DocX 从单词表中删除单元格
【发布时间】:2015-06-18 18:15:13
【问题描述】:

如何使用 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);

它们都不会删除任何单元格。

【问题讨论】:

    标签: c# docx novacode-docx


    【解决方案1】:

    我最近一直在使用 Novacode DocX。我已经意识到,很多类的方法都是继承的,没有被覆盖。一个例子是 cellcontainer 继承 Remove() 并且永远不会被覆盖以执行您期望它执行的操作。 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);
    

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

    【讨论】:

      【解决方案2】:

      您可能必须将表格保存回文档中。
      试试

      1. 将表格附加到文档的末尾。如果缺少单元格
      2. 删除并替换文档中的表格。

      【讨论】:

      • 我尝试在文档末尾附加表格,但它仍然包含我要删除的单元格:-(
      【解决方案3】:

      您必须自己从单元元素中清除子 XML,因为 NovaCode DocX Api 没有正确处理它:

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

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

      【讨论】:

        【解决方案4】:

        Table 类中你可以使用方法

        MergeCells(int, int)
        

        MergeCellsInColumn(int, int, int)
        

        “删除”单元格。

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

        【讨论】:

          猜你喜欢
          • 2018-09-14
          • 1970-01-01
          • 2016-01-19
          • 2016-03-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-08-29
          • 2018-09-28
          相关资源
          最近更新 更多