我有一个包含多个 Rich Text Content Control
的 word 文件,我想更改它的文本。我使用此代码。
using (WordprocessingDocument theDoc = WordprocessingDocument.Open(docName, true))
{
MainDocumentPart mainPart = theDoc.MainDocumentPart;
foreach (SdtElement sdt in mainPart.Document.Descendants<SdtElement>())
{
SdtAlias alias = sdt.Descendants<SdtAlias>().FirstOrDefault();
if (alias != null)
{
string sdtTitle = alias.Val.Value;
var t = sdt.Descendants<Text>().FirstOrDefault();
t.Text="Atul works at Microsoft as a .NET consultant. As a consultant his job is to design, develop and deploy";
}
}
}
它是用旧文本添加新文本。但是我想替换
这个!!!
最佳答案
您只检索和更新 sdtContent 的第一个文本。 要全部替换,最简单的方法是:
- 删除所有文本
- 添加新文本
更新您的代码:
if (alias != null)
{
// delete all paragraph of the sdt
sdt.Descendants<Paragraph>().ToList().ForEach(p => p.Remove());
// insert your new text, who is composed of:
// - A Paragraph
// - A Run
// - A Text
sdt.Append(new Paragraph(new Run(new Text("As a consultant his job is to design, develop and love poney."))));
}
编辑:我忘记添加段落和运行
您可以在此处查看如何构建 SdtContent https://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.sdtcontentblock(v=office.14).aspx
关于c# - 替换 OpenXML 中内容控件的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31750228/