温馨提示×

C#如何查看DOCX文件内容

c#
小樊
82
2024-08-29 03:59:28
栏目: 编程语言

要在C#中查看DOCX文件的内容,您可以使用OpenXML库。这是一个简单的示例,说明如何读取DOCX文件的文本内容:

  1. 首先,安装DocumentFormat.OpenXml库。在Visual Studio中,打开“NuGet包管理器”并搜索“DocumentFormat.OpenXml”。将其添加到项目中。

  2. 然后,使用以下代码读取DOCX文件的文本内容:

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文件的路径。运行此代码后,控制台将显示DOCX文件的文本内容。

0