简体   繁体   中英

Clone ParagraphProperties in Word using OpenXml SDK 2.0

I am programmly generating new paragraphs in Word document via Open XML SDK 2.0. A have first paragraphs with properties, that i would like to append to all new generated paragraphs.

Somthing like this:

var _texts = new List<string>() { "Text 1", "Text 2", "Text 1", "Text 4"};
var sdtBlock = wordDoc.MainDocumentPart.RootElement.Descendants<Paragraph>().First();
foreach (string _t in _texts)
{
    Paragraph p = new Paragraph();
    p.Append(sdtBlock.ParagraphProperties);
    p.Append(new Run(new Text(_t)));
    sdtBlock.InsertAfterSelf<Paragraph>(p);
}

Executing this code throws an Exception: "Cannot insert the OpenXmlElement "newChild" because it is part of a tree." Any ideas?

You need to use the CloneNode() method to make a copy of the instance of ParagraphProperties that you want to add to your new paragraph, eg

p.Append(sdtBlock.ParagraphProperties.CloneNode(true));

Otherwise, you'll get the exception you described (because you would be adding the original node in two different places in the same document, which is not allowed - and not what you were intending to do).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM