Как подсчитать количество слов, страниц и символов в документе на C# и .NET

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

Подсчет количества слов, страниц и символов в документе без использования сторонних программ и сервисов. Если вам необходимо точно определить качество каких-либо символов в документе, просто воспользуйтесь опцией: СalculateStats();

Вы должны выбрать документ в котором будет рассчитываться количество символов:


               //Load a DOCX file
            string filePath = @"d:\Tempos\words.docx";
            DocumentCore dc = DocumentCore.Load(filePath);
Следующий шаг - вызвать опцию обновления и подсчитать количество символов:

             dc.CalculateStats();

В результате подсчета Document.Net предоставляет Вам полную статистику:

Вы можете найти дополнительную информацию о Document Properties

Отлично сработано!

Полный код

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

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

            CalculateStatistics();
        }
		
        /// <summary>
        /// Calculates the number of words, pages and characters in a document.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/counting-words-paragraphs-net-csharp-vb.php
        /// </remarks>
        static void CalculateStatistics()
        {
            // Load a DOCX file.
            string filePath = @"..\..\..\words.docx";

            DocumentCore dc = DocumentCore.Load(filePath);

            // Update and count the number of words and pages in the file.
            dc.CalculateStats();

            // Show statistics.
            Console.WriteLine("Pages: {0}", dc.Document.Properties.BuiltIn[BuiltInDocumentProperty.Pages]);
            Console.WriteLine("Paragraphs: {0}", dc.Document.Properties.BuiltIn[BuiltInDocumentProperty.Paragraphs]);
            Console.WriteLine("Words: {0}", dc.Document.Properties.BuiltIn[BuiltInDocumentProperty.Words]);
            Console.WriteLine("Characters: {0}", dc.Document.Properties.BuiltIn[BuiltInDocumentProperty.Characters]);
            Console.WriteLine("Characters with spaces: {0}", dc.Document.Properties.BuiltIn[BuiltInDocumentProperty.CharactersWithSpaces]);
        }
    }
}

Download

Imports System
Imports System.IO
Imports SautinSoft.Document

Module Sample
    Sub Main()
        CalculateStatistics()
    End Sub
    ''' Get your free 30-day key here:   
    ''' https://sautinsoft.com/start-for-free/
    ''' <summary>
    ''' Calculates the number of words, pages and characters in a document.
    ''' </summary>
    ''' <remarks>
    ''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/counting-words-paragraphs-net-csharp-vb.php
    ''' </remarks>
    Sub CalculateStatistics()
        ' Load a DOCX file.
        Dim filePath As String = "..\..\..\words.docx"

        Dim dc As DocumentCore = DocumentCore.Load(filePath)

        ' Update and count the number of words and pages in the file.
        dc.CalculateStats()

        ' Show statistics.
        Console.WriteLine("Pages: {0}", dc.Document.Properties.BuiltIn(BuiltInDocumentProperty.Pages))
        Console.WriteLine("Paragraphs: {0}", dc.Document.Properties.BuiltIn(BuiltInDocumentProperty.Paragraphs))
        Console.WriteLine("Words: {0}", dc.Document.Properties.BuiltIn(BuiltInDocumentProperty.Words))
        Console.WriteLine("Characters: {0}", dc.Document.Properties.BuiltIn(BuiltInDocumentProperty.Characters))
        Console.WriteLine("Characters with spaces: {0}", dc.Document.Properties.BuiltIn(BuiltInDocumentProperty.CharactersWithSpaces))
    End Sub
End Module

Download


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



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

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