c# – 带有OpenXML SDK 2.0的tableCell文本中的对齐

前端之家收集整理的这篇文章主要介绍了c# – 带有OpenXML SDK 2.0的tableCell文本中的对齐前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在表格单元格中使用Open XML应用文本对齐方式.

我不明白为什么它没有应用.

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

谢谢你的帮助!

解决方法

如果您将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文档中还是用单词查看?

原文链接:https://www.f2er.com/csharp/97733.html

猜你在找的C#相关文章