C#如何查看DOCX文件內(nèi)容

c#
小樊
82
2024-08-29 03:59:28
欄目: 編程語言

要在C#中查看DOCX文件的內(nèi)容,您可以使用OpenXML庫。這是一個(gè)簡單的示例,說明如何讀取DOCX文件的文本內(nèi)容:

  1. 首先,安裝DocumentFormat.OpenXml庫。在Visual Studio中,打開“NuGet包管理器”并搜索“DocumentFormat.OpenXml”。將其添加到項(xiàng)目中。

  2. 然后,使用以下代碼讀取DOCX文件的文本內(nèi)容:

using System;
using System.IO;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

namespace ReadDocxFileContent
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"C:\path\to\your\docx\file.docx";
            string content = ReadDocxFileContent(filePath);
            Console.WriteLine("Content of the DOCX file:");
            Console.WriteLine(content);
        }

        public static string ReadDocxFileContent(string filePath)
        {
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException("The file does not exist.", filePath);
            }

            StringBuilder contentBuilder = new StringBuilder();

            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(filePath, false))
            {
                Body body = wordDoc.MainDocumentPart.Document.Body;
                foreach (var element in body.Elements())
                {
                    if (element is Paragraph paragraph)
                    {
                        foreach (var run in paragraph.Elements<Run>())
                        {
                            foreach (var text in run.Elements<Text>())
                            {
                                contentBuilder.Append(text.Text);
                            }
                        }
                    }
                }
            }

            return contentBuilder.ToString();
        }
    }
}

filePath變量更改為您要讀取的DOCX文件的路徑。運(yùn)行此代碼后,控制臺(tái)將顯示DOCX文件的文本內(nèi)容。

0