如何使所有行具有相同的大小?

How to make all rows have same size?

我是 openxml 的新手,我正在尝试学习基础知识。我一直在尝试创建具有不同属性的 table,但无法通过问题。我需要使 table 中的所有行都具有相同的宽度,而忽略它们的列数。 这是我的代码:

 public static Table createTable(String[][] data)
     {
         Table table = new Table();

         table.AppendChild<TableProperties>(createTableProps());
         for (var i = 0; i < data.Length; i++)
         {
             var tr = new TableRow();
             for (var j = 0; j < data[i].Length; j++)
             {
                 int size = 1200 / data[i].Length;
                 var tc = new TableCell();

                 tc.Append(new TableCellProperties(new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = size.ToString()}));


                Paragraph para = new Paragraph(runTools.getRun(16, "Tahoma", new Text(data[i][j])));

                 tc.Append(para);

                 // Assume you want columns that are automatically sized.
                /* TableCellWidth tcw = new TableCellWidth{Type = TableWidthUnitValues.Auto };
                 tcw.Width = new StringValue("500");
                 tc.Append(new TableCellProperties(tcw));*/

                 tr.Append(tc);
             }
             table.Append(tr);
         }
         return table;
     }

这是我需要的:

您需要将 GridSpan 添加到最上面的列,以便它跨越 2 列。调整列的宽度不起作用,因为单元格不能比列的其余部分宽。

来自documentation for GridSpan

This property allows cells to have the appearance of being merged, as they span vertical boundaries of other cells in the table

在您的代码中,您可以添加对 data[i].Length == 1 的检查 - 如果是,则您可以向该单元格添加跨度以跨越 2 个单元格。例如:

for (var i = 0; i < data.Length; i++)
{
    var tr = new TableRow();
    for (var j = 0; j < data[i].Length; j++)
    {
        var tc = new TableCell();

        tc.Append(new TableCellProperties(new TableCellWidth() 
                                             { Type = TableWidthUnitValues.Auto }));

        Paragraph para = new Paragraph(runTools.getRun(16, "Tahoma", new Text(data[i][j])));

        if (data[i].Length == 1)
        {
            //add a GridSpan with a value of 2 so this cell spans across 2 columns
            tc.TableCellProperties.AppendChild(new GridSpan() { Val = 2 });
            //center justify the text
            if (para.ParagraphProperties == null)
                para.ParagraphProperties = new ParagraphProperties();

            para.ParagraphProperties.Justification = new Justification()
                                                        { Val = JustificationValues.Center };
        }

        tc.Append(para);

        tr.Append(tc);
    }
    table.Append(tr);
}