我正在通过 Open XML SDK 2.0 在 Word 文档中以编程方式生成新段落。 A 具有带有属性的第一段,我想将其附加到所有新生成的段落。
像这样的东西:
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);
}
执行此代码会引发异常:“无法插入 OpenXmlElement“newChild”,因为它是树的一部分。” 有什么想法吗?
最佳答案
您需要使用 CloneNode()
方法复制要添加到新段落的 ParagraphProperties
实例,例如
p.Append(sdtBlock.ParagraphProperties.CloneNode(true));
否则,您将得到您所描述的异常(因为您将在同一文档的两个不同位置添加原始节点,这是不允许的 - 而不是您打算做的)。
关于c# - 使用 OpenXml SDK 2.0 在 Word 中克隆 ParagraphProperties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13759469/