Загрузить существующий документ DOCX и рассчитать все объекты «Run», используя C# и .NET.

  1. Добавьте SautinSoft.Document из Nuget.
  2. Загрузите документ DOCX.
  3. Найдите и подсчитайте все запущенные объекты.

Полный код

using System.IO;
using System.Linq;
using SautinSoft.Document;

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

            CalculateRuns();
        }
        /// <summary>
        /// Loads an existing DOCX document and calculates all 'Run' objects.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/run-element-text-in-docx-document-net-csharp-vb.php
        /// </remarks>
        static void CalculateRuns()
        {
            string filePath = @"..\..\..\example.docx";
            DocumentCore dc = DocumentCore.Load(filePath);
            string filePathResult = @"Result-file.docx";

            foreach (Paragraph par in dc.GetChildElements(true,ElementType.Paragraph))
            {
                int totalRuns = par.GetChildElements(true, ElementType.Run).Count();

                Run r = new Run(dc, "<<This paragraph contains " + totalRuns.ToString() + " Run(s)>>", new CharacterFormat() { BackgroundColor = Color.Yellow, Size = 10, FontColor = Color.Black });
                par.Content.End.Insert(r.Content);
            }
            dc.Save(filePathResult);
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePathResult) { UseShellExecute = true });
        }
    }
}

Download

Imports System
Imports System.IO
Imports System.Linq
Imports SautinSoft.Document

Module Sample
    Sub Main()
        CalculateRuns()
    End Sub
    ''' Get your free 30-day key here:   
    ''' https://sautinsoft.com/start-for-free/
    ''' <summary>
    ''' Loads an existing DOCX document and calculates all 'Run' objects.
    ''' </summary>
    ''' <remarks>
    ''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/run-element-text-in-docx-document-net-csharp-vb.php
    ''' </remarks>
    Sub CalculateRuns()
        Dim filePath As String = "..\..\..\example.docx"
        Dim dc As DocumentCore = DocumentCore.Load(filePath)
        Dim filePathResult As String = "Result-file.docx"

        For Each par As Paragraph In dc.GetChildElements(True, ElementType.Paragraph)
            Dim totalRuns As Integer = par.GetChildElements(True, ElementType.Run).Count()

            Dim r As Run = New Run(dc, "<<This paragraph contains " & totalRuns.ToString() & " Run(s)>>", New CharacterFormat() With {
                    .BackgroundColor = Color.Yellow,
                    .Size = 10,
                    .FontColor = Color.Black
                })
            par.Content.End.Insert(r.Content)
        Next par
        dc.Save(filePathResult)
        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(filePathResult) With {.UseShellExecute = True})
    End Sub
End Module

Download


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



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

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