Search code examples
.net-corems-wordopenxml-sdk

Remove Empty from word document using Open XMl in >net Core


Removing the empty line from the word document the using Open Xml in .Net core


Solution

  • To delete the line you also have to delete the paragraph, this is due to the structure of word:

    <w:p>
        <w:r>
            <w:t>ClientName</w:t>
        </w:r>
    </w:p>
    

    First there is the paragraph and inside there is the text, if there is no text it is a blank paragraph.

    What you were doing was deleting the text, but you also had to remove the paragraph.

    Try the following to see if it helps.

    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open("WordPath", true))
    {
        foreach (Paragraph paragraph in wordDoc.MainDocumentPart.Document.Body.Descendants<Paragraph>())
        {
             Text text = paragraph.Descendants<Text>().FirstOrDefault();
             if (text != null)
             {
                 if (text.Text.Equals("ClientName"))
                 {
                     paragraph.Remove();
                 }
             }
        }
    }
    

    More information can be found in the documentation