我想在表格单元格中使用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;
}
}
谢谢你的帮助!
答案 0 :(得分:15)
如果您将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文档中还是以单词形式查看?
答案 1 :(得分:0)
ParagraphProperties节点无效的原因是节点的ORDER在这里很重要。
您(相当合理!)在运行后将段落属性添加到段落节点。您可能以为该软件将首先考虑该节点,无论其指定的顺序是什么。但是,这是Microsoft Word,而确实很重要。
您需要在运行之前附加ParagraphProperties节点。
我自己也遇到了同样的问题。附加ParagraphProperties首先解决了该问题。