我有一个具有multy 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";
}
}
}
使用旧文本添加新文本。但我想replace
这个!!!
答案 0 :(得分:1)
您只需检索并更新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