如何使用C#逐行读取docx文件?

时间:2019-05-12 21:08:41

标签: c# openxml docx

我正在尝试使用Open XML库读取像这样的docx文件=

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

我的代码是=

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();
            }
        }

但是读取的字符串是这个=

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

如何逐行阅读?

1 个答案:

答案 0 :(得分:1)

要遍历段落:

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();
}