3

I have a word file that have multy Rich Text Content Control I want to change text of it. I Use this code .

 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";
        }
    }
 }

It is add new text with old text. But i want to replace this!!!

Cindy Meister
  • 25,071
  • 21
  • 34
  • 43
ar.gorgin
  • 4,765
  • 12
  • 61
  • 100

1 Answers1

3

You only retrieve and update the first Text of your sdtContent. To replace all of it, the simples way is:

  • Delete all text
  • Add the new text

Update your code with:

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."))));
}

edit: I forget to add the paragraph and the run

You can see how is build a SdtContent here https://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.sdtcontentblock(v=office.14).aspx

Sadegh
  • 4,181
  • 9
  • 45
  • 78
Maxime Porté
  • 1,034
  • 8
  • 13
  • Thanks, but i have a template file that every ContentControl have a format and i don't delete it. I want to Replace text. – ar.gorgin Aug 01 '15 at 04:06
  • Could you give your xml, before replacing the text and after replacing it – Maxime Porté Aug 01 '15 at 06:37
  • I do not understand your solution. – ar.gorgin Aug 01 '15 at 07:00
  • in openxml your text can be split in differents ``. The principe is to suppress all text and add your new one. It's a replace. But it would be muuuuuch simpler if you share your xml (cause here, I propose a solution in the blind, and I can't assure it works like that without changes) – Maxime Porté Aug 01 '15 at 08:20
  • Thanks, i use this. `Text newText = new Text("value"); Run newRun = new Run(); newRun.Append(newText);sdt.Append(newRun);` but when open word i get error that don't open. – ar.gorgin Aug 01 '15 at 14:55
  • I edit the code, but once again, it would be really much simpler if you edit your question with an example of your xml – Maxime Porté Aug 01 '15 at 15:42
  • I use this but get error again. I use this `sdt.Descendants).ToList().ForEach(i => i.Text=string.Empty);` it is ok, but when value is empty, i get a break line. I want to remove this break line. How do i i? – ar.gorgin Aug 01 '15 at 15:51
  • " ... love poney " ? – Shane Mar 02 '22 at 08:32