6

我想在带有 OpenXML 的表格中的表格单元格中应用文本对齐。

我不明白为什么不应用它。

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

谢谢你的帮助!

4

2 回答 2

17

如果您要将paragraphProperties 应用于父单元格而不是段落,它是否有效?

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

// Use System.Nullable<T>.HasValue instead of the null check.
if (justification.HasValue)
{
    // Using System.Nullable<T>.Value to obtain the value and resolve a warning 
    // that occurs when using 'justification' by itself.
    paragraphProperties.AppendChild<Justification>(new Justification() { Val = justification.Value });
}

// append the paragraphProperties to the tableCell rather than the paragraph element
tableCell.AppendChild<ParagraphProperties>(paragraphProperties);
tableCell.AppendChild<Paragraph>(paragraph);
Console.WriteLine(table.OuterXml);

table.OuterXml 之前:

<w:tbl xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
  <w:tr>
    <w:tc>
      <w:p>
        <w:r>
          <w:t>test</w:t>
        </w:r>
        <w:pPr>
          <w:jc w:val="center" />
        </w:pPr>
      </w:p>
    </w:tc>
  </w:tr>
</w:tbl>   

table.OuterXml 之后:

<w:tbl xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
    <w:tr>
    <w:tc>
        <w:pPr>
        <w:jc w:val="center" />
        </w:pPr>
        <w:p>
        <w:r>
            <w:t>test</w:t>
        </w:r>
        </w:p>
    </w:tc>
    </w:tr>
</w:tbl>

我对 OpenXml 相当陌生。结果是否保存到word文档并在word中查看?

于 2012-08-30T01:02:42.717 回答
0

ParagraphProperties 节点无效的原因是节点的顺序在这里很重要。

您正在(相当合理!)在运行之后将段落属性添加到段落节点。您可能会认为软件会首先考虑该节点,无论它指定的顺序是什么。但是,这是 Microsoft Word,顺序确实很重要。

您需要在运行之前附加 ParagraphProperties 节点。

我自己也有同样的问题。附加 ParagraphProperties 首先解决了这个问题。

于 2018-11-29T23:02:20.203 回答