Justification in text from tableCell with OpenXML SDK 2.0

Viewed 8674

I want to apply a text alignment in table cell in a table with OpenXML.

I don't understand why it is not applied.

Table table = new Table();
TableRow tableHeader = new TableRow();
table.AppendChild<TableRow>(tableHeader);
TableCell tableCell = new TableCell();
tableHeader.AppendChild<TableCell>(tableCell);
Paragraph paragraph = new Paragraph(new Run(new Text("test")));
ParagraphProperties paragraphProperties = new ParagraphProperties();
JustificationValues? justification = GetJustificationFromString("centre");
if (justification != null)
{
     paragraphProperties.AppendChild<Justification>(new Justification() { Val = justification });
}
paragraph.AppendChild<ParagraphProperties>(paragraphProperties);
tableCell.AppendChild<Paragraph>(paragraph);


public static JustificationValues? GetJustificationFromString(string alignment)
{
    switch(alignment)
    {
        case "centre" : return JustificationValues.Center;
        case "droite" : return JustificationValues.Right;
        case "gauche" : return JustificationValues.Left;
        default: return null;
    }
}

Thx for you help !

2 Answers

The reason that the ParagraphProperties node is having no effect is that the ORDER of the nodes matters here.

You are (quite reasonably!) adding the paragraph properties to the paragraph node AFTER the Run. You would have thought that the software would consider that node first whichever order it was specified in. However, this is Microsoft Word and the order does matter.

You need to append the ParagraphProperties node BEFORE the run.

I had exactly the same issue myself. Appending the ParagraphProperties first fixed the issue.

Related