keep table(rows) together with OpenXML SDK 2.5

我是研究僧i 提交于 2019-12-12 20:56:21

问题


I'd like to generate multiple tables with 2 rows each inside of a word document. But I want to keep these two rows together (if possible).

  1. new KeepNext()on the first row doesn't work
  2. new KeepNext()on the last paragraph of the first row doesn't work
  3. new CantSplit() on the table doesn't work

In all cases the second row (if too large) lands on the second page. A new CantSplit() on the last cell ( the one with large content) avoids a break of the cell. But none of the options avoids a split of the table (rowwise).


回答1:


You need to add a KeepNext to each row to keep them together. The XML output in document.xml should be something akin to:

This code successfully creates a table with 2 rows that will stay together across pages:

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

getting all tables

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


来源:https://stackoverflow.com/questions/24995999/keep-tablerows-together-with-openxml-sdk-2-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!