0
我用OpenXML填写了一种模板Word文件(不是.dot)。我碰到的问题是,当我添加新文本到文档使用Word文档的默认字体和字体大小。 我希望它使用我添加的段落的字体和大小,或者我添加到的现有表格中的格式。从openxml获取字体信息的更好方法
我找到了一个方法,但我不认为它是一个好方法。 那么......有没有更好的方法呢?
这是一个段落
private RunProperties GetRunPropertyFromParagraph(Paragraph paragraph)
{
var runProperties = new RunProperties();
var fontname = "Calibri";
var fontSize = "18";
try
{
fontname =
paragraph.GetFirstChild<ParagraphProperties>()
.GetFirstChild<ParagraphMarkRunProperties>()
.GetFirstChild<RunFonts>()
.Ascii;
}
catch
{
//swallow
}
try
{
fontSize =
paragraph.GetFirstChild<Paragraph>()
.GetFirstChild<ParagraphProperties>()
.GetFirstChild<ParagraphMarkRunProperties>()
.GetFirstChild<FontSize>()
.Val;
}
catch
{
//swallow
}
runProperties.AppendChild(new RunFonts() { Ascii = fontname });
runProperties.AppendChild(new FontSize() { Val = fontSize });
return runProperties;
}
这从TableCell的
private RunProperties GetRunPropertyFromTableCell(TableRow rowCopy, int cellIndex)
{
var runProperties = new RunProperties();
var fontname = "Calibri";
var fontSize = "18";
try
{
fontname =
rowCopy.Descendants<TableCell>()
.ElementAt(cellIndex)
.GetFirstChild<Paragraph>()
.GetFirstChild<ParagraphProperties>()
.GetFirstChild<ParagraphMarkRunProperties>()
.GetFirstChild<RunFonts>()
.Ascii;
}
catch
{
//swallow
}
try
{
fontSize =
rowCopy.Descendants<TableCell>()
.ElementAt(cellIndex)
.GetFirstChild<Paragraph>()
.GetFirstChild<ParagraphProperties>()
.GetFirstChild<ParagraphMarkRunProperties>()
.GetFirstChild<FontSize>()
.Val;
}
catch
{
//swallow
}
runProperties.AppendChild(new RunFonts() { Ascii = fontname });
runProperties.AppendChild(new FontSize() { Val = fontSize });
return runProperties;
}
代码工作。至少在我尝试过的文件中。 但好像做这件事的可怕的方式,但我还没有找到一个更好的解决方案,如果您有一个,请分享:)
这种方法的问题在于RunProperties只在运行时才存在。可能有一段没有Run的段落,在这种情况下,我认为*您需要ParagraphMarkRunProperties,但不知道如何在将段落添加到段落时使用该段落。 – cjb110 2013-09-26 09:12:52