Burak Karasoy Burak Karasoy - 15 days ago 5
C# Question

How to make all rows have same size?

I'm new in openxml and I am trying to learn basics. I have been trying to create tables with different properties but couldn't pass an issue. I need to make all rows have same width in the table ignoring column counts they have.
This is my code:

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


This is what I need:

enter image description here

Answer

You need to add a GridSpan to your top column in order for it to span across 2 columns. Adjusting the width of your column won't work as a cell can't be wider than the rest of the column.

From the 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

In your code you could add a check for data[i].Length == 1 - if it is then you can add a span to that cell to span 2 cells. For example:

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