Ege
Ege

Reputation: 178

How to read docx files line by line with c#?

I am trying to use Open XML library to read a docx file like this =

White Noise
Rain Sounds
1

Hot N*gga
Bobby Shmurda
2

Ric Flair Drip (& Metro Boomin)
21 Savage , Offset , Metro Boomin
3

Plastic
Jaden
4

my code is =

public static void OpenWordprocessingDocumentReadonly(string filepath)
        {
            // Open a WordprocessingDocument based on a filepath.
            using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(filepath, false))
            {
                // Assign a reference to the existing document body.  
                Body body = wordDocument.MainDocumentPart.Document.Body;


                Console.Write(body.InnerText);
                Console.ReadKey();
            }
        }

but readed string is this =

White NoiseRain Sounds1Hot N*ggaBobby Shmurda2Ric Flair Drip (& Metro Boomin)21 Savage , Offset , Metro Boomin3PlasticJaden

How to read line by line ?

Upvotes: 1

Views: 3327

Answers (1)

Slai
Slai

Reputation: 22876

To loop over paragraphs :

using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(filepath, false))
{
    var paragraphs = wordDocument.MainDocumentPart.RootElement.Descendants<Paragraph>();
    foreach (var paragraph in paragraphs)
    {
        Console.WriteLine(paragraph.InnerText);
    }
    Console.ReadKey();
}

Upvotes: 4

Related Questions