簡體   English   中英

使用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();

我需要將樣式應用於此元素。 我該怎么辦?

我嘗試使用“用於Microsoft Office的Open XML SDK 2.5生產率工具”看到生成的代碼,這對我有啟發:

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個錯誤: http://imagizer.imageshack.us/a/img633/1176/7QX5So.png

全尺寸

我找到了解決方案。 我搜索第一段並在其上應用我的自定義樣式。

// 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM