使用 OpenXML 在 Word 文档中的内容控件上应用样式

Apply style on Content Control in a Word Document using OpenXML

我正在尝试使用 OpenXML SDK 和 Word Document Generator 生成 Word 文档。我需要在 ContentControls(重复部分)上应用我的自定义样式。

对于递归占位符,我使用

foreach (var item in list)
{
    var datacontext = new OpenXmlElementDataContext()
    {
        Element = openXmlElementDataContext.Element,
        DataContext = item.Value
    };
    var clonedElement = CloneElementAndSetContentInPlaceholders(datacontext);
    SetContentOfContentControl(clonedElement, item.Value);
}
openXmlElementDataContext.Element.Remove();

我需要在此元素上应用我的样式。 我该怎么做?

我尝试查看使用 "Open XML SDK 2.5 Productivity Tool for Microsoft Office" 生成的代码来启发我:

var moduleDatacontext = new OpenXmlElementDataContext()
{
    Element = openXmlElementDataContext.Element,
    DataContext = module.Valeur
};
var moduleClonedElement = CloneElementAndSetContentInPlaceholders(moduleDatacontext);

var sdtProperties1 = new SdtProperties();
var styleId1 = new StyleId() { Val = "FormationTitre2" };

ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties();
RunFonts runFonts1 = new RunFonts() { ComplexScriptTheme = ThemeFontValues.MinorHighAnsi };

paragraphMarkRunProperties1.Append(runFonts1);

sdtProperties1.Append(styleId1);
sdtProperties1.Append(paragraphMarkRunProperties1);

Run run1 = new Run() { RsidRunProperties = "00C463E5" };

RunProperties runProperties1 = new RunProperties();
RunFonts runFonts2 = new RunFonts() { ComplexScriptTheme = ThemeFontValues.MinorHighAnsi };

runProperties1.Append(runFonts2);

run1.Append(runProperties1);

moduleClonedElement.Append(sdtProperties1);
moduleClonedElement.Append(run1);

当我打开生成的文档时,出现此错误:

我们很抱歉。我们无法打开“...docx”,因为我们发现它的内容有问题。

我验证了文档,发现了 15 个错误:

Full Size

我找到了解决办法。我搜索第一段并在其上应用我的自定义样式。

// clone element
var clonedElement = CloneElementAndSetContentInPlaceholders(datacontext);

// search the first created paragraph on my clonedElement
Paragraph p = clonedElement.Descendants<Paragraph>().FirstOrDefault();
if (p != null)
    p.PrependChild<ParagraphProperties>(new ParagraphProperties());
// get the paragraph properties
ParagraphProperties pPr = p.Elements<ParagraphProperties>().First();
// apply style
pPr.ParagraphStyleId = new ParagraphStyleId { Val = "FormationTitre2" };
// set content of content control
SetContentOfContentControl(clonedElement, item.Value);