Как получить содержимое документа с помощью C# и .NET

  1. Добавьте SautinSoft.Document из Nuget.
  2. Загрузите документ DOCX.
  3. Получите содержимое каждого абзаца.
  4. Получите содержимое каждого прогона с красным цветом текста.

Полный код

using System;
using SautinSoft.Document;
using System.Text;

namespace Sample
{
    class Sample
    {
      
        static void Main(string[] args)
        {
            // Get your free 30-day key here:   
            // https://sautinsoft.com/start-for-free/

            GetContent();
        }

		/// <summary>
        /// How to get a content from a document.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/get-content-net-csharp-vb.php
        /// </remarks>
        public static void GetContent()
        {
            // Path to an input document.
            string documentPath = @"..\..\..\example.docx";

            DocumentCore dc = DocumentCore.Load(documentPath);

            StringBuilder sb = new StringBuilder();

            // Get content of each paragraph in the document.
            foreach (Paragraph par in dc.GetChildElements(true, ElementType.Paragraph))
            {
                // The property 'Content' returns the content as ContentRange.
                // Get content and append it into StringBuilder.
                sb.AppendFormat("Paragraph: {0}", par.Content.ToString());
                sb.AppendLine();
            }

            // Get content of each Run where the text color is Red.
            foreach (Run run in dc.GetChildElements(true, ElementType.Run))
            {
                if (run.CharacterFormat.FontColor == Color.Red)
                {
                    // The property 'Content' returns the content as ContentRange.
                    // Get content and append it into StringBuilder.
                    sb.AppendFormat("Red color: {0}", run.Content.ToString());
                    sb.AppendLine();
                }
            }
            Console.WriteLine(sb.ToString());
            Console.ReadKey();
        }
    }
}

Download

Imports System
Imports SautinSoft.Document
Imports System.Text

Module Sample
    Sub Main()
        GetContent()
    End Sub
    ''' Get your free 30-day key here:   
    ''' https://sautinsoft.com/start-for-free/
    ''' <summary>
    ''' How to get a content from a document.
    ''' </summary>
    ''' <remarks>
    ''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/get-content-net-csharp-vb.php
    ''' </remarks>
    Sub GetContent()
        ' Path to an input document.
        Dim documentPath As String = "..\..\..\example.docx"

        Dim dc As DocumentCore = DocumentCore.Load(documentPath)

        Dim sb As New StringBuilder()

        ' Get content of each paragraph in the document.
        For Each par As Paragraph In dc.GetChildElements(True, ElementType.Paragraph)
            ' The property 'Content' returns the content as ContentRange.
            ' Get content and append it into StringBuilder.
            sb.AppendFormat("Paragraph: {0}", par.Content.ToString())
            sb.AppendLine()
        Next par

        ' Get content of each Run where the text color is Red.
        For Each run As Run In dc.GetChildElements(True, ElementType.Run)
            If run.CharacterFormat.FontColor = Color.Red Then
                ' The property 'Content' returns the content as ContentRange.
                ' Get content and append it into StringBuilder.
                sb.AppendFormat("Red color: {0}", run.Content.ToString())
                sb.AppendLine()
            End If
        Next run
        Console.WriteLine(sb.ToString())
        Console.ReadKey()
    End Sub
End Module

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу [email protected] или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.