Как удалить строки с указанным текстом из таблицы с помощью C# и .NET


В этом примере кода мы найдем пожилых людей в возрасте 90 лет и старше из списка и удалим оставшиеся строки.

Загрузите полученный файл: result - long-livers.pdf

Полный код

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

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

            FindTextFromTable();
        }

        /// <summary>
        /// How to remove the rows with the specified text from a table.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/from-customers-find-text-from-table-net-csharp-vb.php
        /// </remarks>
        public static void FindTextFromTable()
        {
            int longLiverMinYears = 90;

            string inpFile = @"..\..\..\example.docx";
            string outFile = Path.ChangeExtension(inpFile, ".pdf");

            // Load a document with a table containing various persons with different age.
            DocumentCore dc = DocumentCore.Load(inpFile);

            // Find a first table in the document.
            Table table = (Table)dc.GetChildElements(true, ElementType.Table).First();

            // Loop by the all rows from the end.
            // Find long-livers.
            bool isLongLiver = false;

            for (int r = table.Rows.Count - 1; r > 0; r--)
            {
                isLongLiver = false;

                // Take the 3rd cell with the birth date.
                TableCell tc = table.Rows[r].Cells[2];

                // Get the birth date.
                DateTime birthDate = DateTime.Now;
                if (DateTime.TryParse(tc.Content.ToString(), CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.None, out birthDate))
                {
                    // Get the person age.
                    // Remove the row if the person isn't long-liver.
                    if (CalculateAge(birthDate) >= longLiverMinYears)
                        isLongLiver = true;
                }
                // Remove the row if it doesn't contain a long-liver.
                if (!isLongLiver)
                    table.Rows.RemoveAt(r);
            }

            // Save the document as PDF.
            dc.Save(outFile, new PdfSaveOptions());

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
        }
        private static int CalculateAge(DateTime dateOfBirth)
        {
            int age = 0;
            age = DateTime.Now.Year - dateOfBirth.Year;
            if (DateTime.Now.DayOfYear < dateOfBirth.DayOfYear)
                age = age - 1;
            return age;
        }
    }
}

Download

Imports System
Imports System.Globalization
Imports System.IO
Imports System.Linq
Imports SautinSoft.Document
Imports SautinSoft.Document.Tables

Namespace Sample
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			FindTextFromTable()
		End Sub
                ''' Get your free 100-day key here:   
                ''' https://sautinsoft.com/start-for-free/
		''' <summary>
		''' How to remove the rows with the specified text from a table.
		''' </summary>
		''' <remarks>
		''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/from-customers-find-text-from-table-net-csharp-vb.php
		''' </remarks>
		Public Shared Sub FindTextFromTable()
			Dim longLiverMinYears As Integer = 90

			Dim inpFile As String = "..\..\..\example.docx"
			Dim outFile As String = Path.ChangeExtension(inpFile, ".pdf")

			' Load a document with a table containing various persons with different age.
			Dim dc As DocumentCore = DocumentCore.Load(inpFile)

			' Find a first table in the document.
			Dim table As Table = CType(dc.GetChildElements(True, ElementType.Table).First(), Table)

			' Loop by the all rows from the end.
			' Find long-livers.
			Dim isLongLiver As Boolean = False

			For r As Integer = table.Rows.Count - 1 To 1 Step -1
				isLongLiver = False

				' Take the 3rd cell with the birth date.
				Dim tc As TableCell = table.Rows(r).Cells(2)

				' Get the birth date.
				Dim birthDate As Date = Date.Now
				If Date.TryParse(tc.Content.ToString(), CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.None, birthDate) Then
					' Get the person age.
					' Remove the row if the person isn't long-liver.
					If CalculateAge(birthDate) >= longLiverMinYears Then
						isLongLiver = True
					End If
				End If
				' Remove the row if it doesn't contain a long-liver.
				If Not isLongLiver Then
					table.Rows.RemoveAt(r)
				End If
			Next r

			' Save the document as PDF.
			dc.Save(outFile, New PdfSaveOptions())

			' Open the result for demonstration purposes.
			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(outFile) With {.UseShellExecute = True})
		End Sub
		Private Shared Function CalculateAge(ByVal dateOfBirth As Date) As Integer
			Dim age As Integer = 0
			age = Date.Now.Year - dateOfBirth.Year
			If Date.Now.DayOfYear < dateOfBirth.DayOfYear Then
				age = age - 1
			End If
			Return age
		End Function
	End Class
End Namespace

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу support@sautinsoft.com или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



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

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