【问题标题】:keep table(rows) together with OpenXML SDK 2.5将表(行)与 OpenXML SDK 2.5 保持在一起
【发布时间】:2014-07-28 13:07:52
【问题描述】:

我想在一个 word 文档中生成多个表格,每个表格有 2 行。但我想把这两行放在一起(如果可能的话)。

  1. new KeepNext()在第一行不起作用
  2. new KeepNext()第一行最后一段不起作用
  3. 桌子上的new CantSplit() 不起作用

在所有情况下,第二行(如果太大)都位于第二页上。最后一个单元格(内容较大的单元格)上的new CantSplit() 可避免单元格中断。但是没有一个选项可以避免表格的拆分(按行)。

【问题讨论】:

    标签: c# .net-4.5 openxml openxml-sdk wordprocessingml


    【解决方案1】:

    您需要向 每个 行添加一个 KeepNext 以将它们保持在一起。 document.xml 中的 XML 输出应该类似于:

    此代码成功创建了一个包含 2 行的表格,这些表格将跨页保持在一起:

    Table table = wordDoc.MainDocumentPart.Document.Body.AppendChild(new Table());
    
    TableRow row1 = table.AppendChild(new TableRow());
    TableCell cell1 = row1.AppendChild(new TableCell());
    Paragraph para1 = cell1.AppendChild(new Paragraph());
    PreviousParagraphProperties prop1 = para1.AppendChild(new PreviousParagraphProperties());
    KeepNext k = prop1.AppendChild(new KeepNext());
    Run run1 = para1.AppendChild(new Run());
    run1.AppendChild(new Text("This is some long text"));
    
    TableRow row2 = table.AppendChild(new TableRow());
    TableCell cell2 = row2.AppendChild(new TableCell());
    Paragraph para2 = cell2.AppendChild(new Paragraph());
    PreviousParagraphProperties prop2 = para1.AppendChild(new PreviousParagraphProperties());
    KeepNext k2 = prop2.AppendChild(new KeepNext());
    Run run2 = para2.AppendChild(new Run());
    run2.AppendChild(new Text("This is some even longer text"));
    

    【讨论】:

      【解决方案2】:
      i did it like this when I had to apply this to all tables:
      
      private static void AlterTableType(List<Table> t)
          {
              foreach (Table table in t)
              {
                  foreach (TableRow row in table.Descendants<TableRow>())
                  {
                      TableRowProperties trP = new TableRowProperties();
                      CantSplit split = new CantSplit();
                      trP.Append(split);
                      row.AppendChild(trP);
                  }
              }
          }
      

      获取所有表格

      var t = package.MainDocumentPart.Document.Body.Descendants<Table>().ToList()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-12
        • 2017-05-25
        相关资源
        最近更新 更多