【发布时间】:2015-05-19 12:19:44
【问题描述】:
我使用 open XML(Microsoft Word - .docx) 作为文件模板来自动生成其他文档。在模板文档中,我定义了内容控件,并编写了代码来替换这些内容控件中的内容。
内容被替换并生成了文档,但我在努力保持风格。在 Word 中,当检查内容控件的属性时,我选中了“使用样式将文本格式化为空控件:样式”复选框,还选中了“编辑内容时删除内容控件”。当文档由代码生成时,这似乎没有任何影响。
这是我用于替换内容控件中的数据的代码(这里的社区成员很乐意提供帮助)。为了保持格式,我应该怎么做?格式是简单的文本格式,如大小和字体。请指教:
private static void ReplaceTags(MainDocumentPart mainPart, string tagName, string tagValue)
{
//grab all the tag fields
var tagFields = mainPart.Document.Body.Descendants<SdtBlock>().Where
(r => r.SdtProperties.GetFirstChild<Tag>().Val == tagName);
foreach (var field in tagFields)
{
//remove all paragraphs from the content block
field.SdtContentBlock.RemoveAllChildren<DocumentFormat.OpenXml.Wordprocessing.Paragraph>();
//create a new paragraph containing a run and a text element
var newParagraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
var newRun = new DocumentFormat.OpenXml.Wordprocessing.Run();
var newText = new DocumentFormat.OpenXml.Wordprocessing.Text(tagValue);
newRun.Append(newText);
newParagraph.Append(newRun);
//add the new paragraph to the content block
field.SdtContentBlock.Append(newParagraph);
}
}
【问题讨论】:
标签: c# ms-word openxml openxml-sdk