How to Read Table in Documents

This article was translated from English: Does it need improvement?
Translated
View the article in English

Lassen Sie uns über das Lesen von Tabellen in Dokumenten sprechen. Die Extraktion von Daten aus Tabellen mit einfachem Tesseract kann herausfordernd sein, da sich der Text oft in Zellen befindet und über das Dokument verteilt ist. Unsere Bibliothek ist jedoch mit einem maschinellen Lernmodell ausgestattet, das für die Erkennung und genaue Extraktion von Tabellendaten trainiert und optimiert wurde.

Für einfache Tabellen können Sie auf eine unkomplizierte Tabellenerkennung vertrauen, während für komplexere Strukturen unsere exklusive ReadDocumentAdvanced-Methode robuste Ergebnisse liefert, indem sie die Tabelle effektiv analysiert und die Daten bereitstellt.

als-Überschrift:2(Schnellstart: Komplexe Tabellenzellen in einem Aufruf extrahieren)

In wenigen Minuten einsatzbereit—dieses Beispiel zeigt, wie ein einzelner IronOCR-Aufruf mit ReadDocumentAdvanced Ihnen detaillierte Tabellenzelldaten aus einem komplexen Dokument liefert. Es demonstriert die Benutzerfreundlichkeit, indem es ein PDF lädt, eine erweiterte Tabellenerkennung anwendet und eine Liste von Zellinformationen direkt zurückgibt.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronOCR with NuGet Package Manager

    PM > Install-Package IronOcr

  2. Copy and run this code snippet.

    var cells = new IronTesseract().ReadDocumentAdvanced(new OcrInput().LoadPdf("invoiceTable.pdf")).Tables.First().CellInfos;
  3. Deploy to test on your live environment

    Start using IronOCR in your project today with a free trial
    arrow pointer

Die folgenden Schritte führen Sie in die ersten Schritte zum Lesen von Tabellen mit IronOCR ein:

class="hsg-featured-snippet">

Minimaler Workflow (5 Schritte)

  1. Laden Sie eine C#-Bibliothek herunter, um Daten aus Tabellen zu extrahieren
  2. Bereiten Sie das Bild und das PDF-Dokument für die Extraktion vor
  3. Setzen Sie die ReadDataTables-Eigenschaft auf true, um die Tabellenerkennung zu aktivieren
  4. Verwenden Sie die ReadDocumentAdvanced-Methode für komplexe Tabellen
  5. Extrahieren Sie die durch diese Methoden erkannten Daten


Einfaches Tabellenbeispiel

Das Setzen der ReadDataTables-Eigenschaft auf true aktiviert die Tabellenerkennung mit Tesseract. Ich habe ein einfaches Tabellen-PDF erstellt, um diese Funktion zu testen, das Sie hier herunterladen können: 'simple-table.pdf'. Einfache Tabellen ohne zusammengeführte Zellen können mit dieser Methode erkannt werden. Für komplexere Tabellen verweisen Sie bitte auf die unten beschriebene Methode.

:path=/static-assets/ocr/content-code-examples/how-to/read-table-in-document-with-tesseract.cs
using IronOcr;
using System;
using System.Data;

// Instantiate OCR engine
var ocr = new IronTesseract();

// Enable table detection
ocr.Configuration.ReadDataTables = true;

using var input = new OcrPdfInput("simple-table.pdf");
var result = ocr.Read(input);

// Retrieve the data
var table = result.Tables[0].DataTable;

// Print out the table data
foreach (DataRow row in table.Rows)
{
    foreach (var item in row.ItemArray)
    {
        Console.Write(item + "\t");
    }
    Console.WriteLine();
}
Imports Microsoft.VisualBasic
Imports IronOcr
Imports System
Imports System.Data

' Instantiate OCR engine
Private ocr = New IronTesseract()

' Enable table detection
ocr.Configuration.ReadDataTables = True

Dim input = New OcrPdfInput("simple-table.pdf")
Dim result = ocr.Read(input)

' Retrieve the data
Dim table = result.Tables(0).DataTable

' Print out the table data
For Each row As DataRow In table.Rows
	For Each item In row.ItemArray
		Console.Write(item & vbTab)
	Next item
	Console.WriteLine()
Next row
$vbLabelText   $csharpLabel

Beispiel zum Lesen von Rechnungen

Eine der häufigsten komplexen Tabellen in Geschäftsumgebungen sind Rechnungen. Rechnungen selbst sind komplexe Tabellen mit Datenzeilen und -spalten. Mit IronOCR nutzen wir die ReadDocumentAdvanced-Methode, um sie hervorragend zu handhaben. Der Prozess umfasst das Scannen des Dokuments, die Identifikation der Tabellenstruktur und die Datenextraktion. In diesem Beispiel verwenden wir die Datei 'invoiceTable.pdf', um zu zeigen, wie IronOCR alle Informationen aus der Rechnung abruft.

Die ReadDocumentAdvanced-Methode erfordert das IronOcr.Extensions.AdvancedScan-Paket, das zusammen mit dem grundlegenden IronOCR-Paket installiert werden muss.

Hinweis: Die erweiterte Abtastung auf dem .NET Framework erfordert, dass das Projekt auf der x64-Architektur ausgeführt wird. Navigieren Sie zur Projektkonfiguration und deaktivieren Sie die Option "Bevorzugt 32-Bit", um dies zu erreichen. Erfahren Sie mehr im folgenden Leitfaden zur Fehlersuche: "Erweiterte Abtastung auf dem .NET Framework".

:path=/static-assets/ocr/content-code-examples/how-to/read-table-in-document-with-ml.cs
using IronOcr;
using System.Linq;

// Instantiate OCR engine
var ocr = new IronTesseract();

using var input = new OcrInput();
input.LoadPdf("invoiceTable.pdf");

// Perform OCR
var result = ocr.ReadDocumentAdvanced(input);

var cellList = result.Tables.First().CellInfos;
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Diese Methode unterteilt die Textdaten des Dokuments in zwei Kategorien: eine von Rahmen eingeschlossen und eine ohne Rahmen. Für die mit Rahmen versehenen Inhalte teilt die Bibliothek sie weiter in Unterabschnitte basierend auf der Tabellenstruktur auf. Die Ergebnisse werden unten angezeigt. Es ist wichtig zu beachten, dass, da diese Methode sich auf Informationen innerhalb von Rahmen konzentriert, zusammengeführte Zellen, die mehrere Zeilen umfassen, als eine einzige Zelle behandelt werden.

Ergebnis

class="content-img-align-center">
class="center-image-wrapper"> Tabelle im Dokument lesen

Hilfsklasse

In der aktuellen Implementation sind die extrahierten Zellen noch nicht richtig organisiert. Jede Zelle enthält jedoch wertvolle Informationen wie X- und Y-Koordinaten, Abmessungen und mehr. Mit diesen Daten können wir eine Hilfsklasse für verschiedene Zwecke erstellen. Nachfolgend sind einige grundlegende Hilfsmethoden aufgeführt:

using System;
using System.Collections.Generic;
using System.Linq;

// A helper class to process table data by sorting cells based on coordinates
public static class TableProcessor
{
    // Method to organize cells by their coordinates (Y top to bottom, X left to right)
    public static List<CellInfo> OrganizeCellsByCoordinates(List<CellInfo> cells)
    {
        // Sort cells by Y (top to bottom), then by X (left to right)
        var sortedCells = cells
            .OrderBy(cell => cell.CellRect.Y)
            .ThenBy(cell => cell.CellRect.X)
            .ToList();

        return sortedCells;
    }

    // Example method demonstrating how to process multiple tables
    public static void ProcessTables(Tables tables)
    {
        foreach (var table in tables)
        {
            var sortedCells = OrganizeCellsByCoordinates(table.CellInfos);

            Console.WriteLine("Organized Table Cells:");

            // Initialize previous Y coordinate
            int previousY = sortedCells.Any() ? sortedCells.First().CellRect.Y : 0;

            foreach (var cell in sortedCells)
            {
                // Print a new line if the Y-coordinate changes, indicating a new row
                if (Math.Abs(cell.CellRect.Y - previousY) > cell.CellRect.Height * 0.8)
                {
                    Console.WriteLine();  // Start a new row
                    previousY = cell.CellRect.Y;
                }

                // Print the cell text followed by a tab
                Console.Write($"{cell.CellText}\t");
            }

            Console.WriteLine("\n--- End of Table ---");  // End of a table
        }
    }

    // Method to extract a specific row by the given index
    public static List<CellInfo> ExtractRowByIndex(TableInfo table, int rowIndex)
    {
        if (table == null || table.CellInfos == null || !table.CellInfos.Any())
        {
            throw new ArgumentException("Table is empty or invalid.");
        }

        var sortedCells = OrganizeCellsByCoordinates(table.CellInfos);
        List<List<CellInfo>> rows = new List<List<CellInfo>>();

        // Group cells into rows based on Y coordinates
        int previousY = sortedCells.First().CellRect.Y;
        List<CellInfo> currentRow = new List<CellInfo>();

        foreach (var cell in sortedCells)
        {
            if (Math.Abs(cell.CellRect.Y - previousY) > cell.CellRect.Height * 0.8)
            {
                // Store the completed row and start a new one
                rows.Add(new List<CellInfo>(currentRow));
                currentRow.Clear();

                previousY = cell.CellRect.Y;
            }

            currentRow.Add(cell);
        }

        // Add the last row if it wasn't added yet
        if (currentRow.Any())
        {
            rows.Add(currentRow);
        }

        // Retrieve the specified row
        if (rowIndex < 0 || rowIndex >= rows.Count)
        {
            throw new IndexOutOfRangeException($"Row index {rowIndex} is out of range.");
        }

        return rows[rowIndex];
    }
}
using System;
using System.Collections.Generic;
using System.Linq;

// A helper class to process table data by sorting cells based on coordinates
public static class TableProcessor
{
    // Method to organize cells by their coordinates (Y top to bottom, X left to right)
    public static List<CellInfo> OrganizeCellsByCoordinates(List<CellInfo> cells)
    {
        // Sort cells by Y (top to bottom), then by X (left to right)
        var sortedCells = cells
            .OrderBy(cell => cell.CellRect.Y)
            .ThenBy(cell => cell.CellRect.X)
            .ToList();

        return sortedCells;
    }

    // Example method demonstrating how to process multiple tables
    public static void ProcessTables(Tables tables)
    {
        foreach (var table in tables)
        {
            var sortedCells = OrganizeCellsByCoordinates(table.CellInfos);

            Console.WriteLine("Organized Table Cells:");

            // Initialize previous Y coordinate
            int previousY = sortedCells.Any() ? sortedCells.First().CellRect.Y : 0;

            foreach (var cell in sortedCells)
            {
                // Print a new line if the Y-coordinate changes, indicating a new row
                if (Math.Abs(cell.CellRect.Y - previousY) > cell.CellRect.Height * 0.8)
                {
                    Console.WriteLine();  // Start a new row
                    previousY = cell.CellRect.Y;
                }

                // Print the cell text followed by a tab
                Console.Write($"{cell.CellText}\t");
            }

            Console.WriteLine("\n--- End of Table ---");  // End of a table
        }
    }

    // Method to extract a specific row by the given index
    public static List<CellInfo> ExtractRowByIndex(TableInfo table, int rowIndex)
    {
        if (table == null || table.CellInfos == null || !table.CellInfos.Any())
        {
            throw new ArgumentException("Table is empty or invalid.");
        }

        var sortedCells = OrganizeCellsByCoordinates(table.CellInfos);
        List<List<CellInfo>> rows = new List<List<CellInfo>>();

        // Group cells into rows based on Y coordinates
        int previousY = sortedCells.First().CellRect.Y;
        List<CellInfo> currentRow = new List<CellInfo>();

        foreach (var cell in sortedCells)
        {
            if (Math.Abs(cell.CellRect.Y - previousY) > cell.CellRect.Height * 0.8)
            {
                // Store the completed row and start a new one
                rows.Add(new List<CellInfo>(currentRow));
                currentRow.Clear();

                previousY = cell.CellRect.Y;
            }

            currentRow.Add(cell);
        }

        // Add the last row if it wasn't added yet
        if (currentRow.Any())
        {
            rows.Add(currentRow);
        }

        // Retrieve the specified row
        if (rowIndex < 0 || rowIndex >= rows.Count)
        {
            throw new IndexOutOfRangeException($"Row index {rowIndex} is out of range.");
        }

        return rows[rowIndex];
    }
}
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports System.Linq

' A helper class to process table data by sorting cells based on coordinates
Public Module TableProcessor
	' Method to organize cells by their coordinates (Y top to bottom, X left to right)
	Public Function OrganizeCellsByCoordinates(ByVal cells As List(Of CellInfo)) As List(Of CellInfo)
		' Sort cells by Y (top to bottom), then by X (left to right)
		Dim sortedCells = cells.OrderBy(Function(cell) cell.CellRect.Y).ThenBy(Function(cell) cell.CellRect.X).ToList()

		Return sortedCells
	End Function

	' Example method demonstrating how to process multiple tables
	Public Sub ProcessTables(ByVal tables As Tables)
		For Each table In tables
			Dim sortedCells = OrganizeCellsByCoordinates(table.CellInfos)

			Console.WriteLine("Organized Table Cells:")

			' Initialize previous Y coordinate
			Dim previousY As Integer = If(sortedCells.Any(), sortedCells.First().CellRect.Y, 0)

			For Each cell In sortedCells
				' Print a new line if the Y-coordinate changes, indicating a new row
				If Math.Abs(cell.CellRect.Y - previousY) > cell.CellRect.Height * 0.8 Then
					Console.WriteLine() ' Start a new row
					previousY = cell.CellRect.Y
				End If

				' Print the cell text followed by a tab
				Console.Write($"{cell.CellText}" & vbTab)
			Next cell

			Console.WriteLine(vbLf & "--- End of Table ---") ' End of a table
		Next table
	End Sub

	' Method to extract a specific row by the given index
	Public Function ExtractRowByIndex(ByVal table As TableInfo, ByVal rowIndex As Integer) As List(Of CellInfo)
		If table Is Nothing OrElse table.CellInfos Is Nothing OrElse Not table.CellInfos.Any() Then
			Throw New ArgumentException("Table is empty or invalid.")
		End If

		Dim sortedCells = OrganizeCellsByCoordinates(table.CellInfos)
		Dim rows As New List(Of List(Of CellInfo))()

		' Group cells into rows based on Y coordinates
		Dim previousY As Integer = sortedCells.First().CellRect.Y
		Dim currentRow As New List(Of CellInfo)()

		For Each cell In sortedCells
			If Math.Abs(cell.CellRect.Y - previousY) > cell.CellRect.Height * 0.8 Then
				' Store the completed row and start a new one
				rows.Add(New List(Of CellInfo)(currentRow))
				currentRow.Clear()

				previousY = cell.CellRect.Y
			End If

			currentRow.Add(cell)
		Next cell

		' Add the last row if it wasn't added yet
		If currentRow.Any() Then
			rows.Add(currentRow)
		End If

		' Retrieve the specified row
		If rowIndex < 0 OrElse rowIndex >= rows.Count Then
			Throw New IndexOutOfRangeException($"Row index {rowIndex} is out of range.")
		End If

		Return rows(rowIndex)
	End Function
End Module
$vbLabelText   $csharpLabel

Häufig gestellte Fragen

Wie kann ich die Tabellendatenerfassung in Dokumenten mit C# verbessern?

Sie können die Tabellendatenerfassung in Dokumenten mit C# verbessern, indem Sie das maschinelle Lernmodell von IronOCR verwenden, das speziell auf die Erkennung und genaue Erfassung komplexer Tabellendaten trainiert wurde. Dieser Ansatz ist effektiver als die Verwendung standardmäßiger OCR-Tools wie Tesseract.

Was ist der Zweck der Methode `ReadDocumentAdvanced` in IronOCR?

Die Methode `ReadDocumentAdvanced` in IronOCR ist dafür ausgelegt, komplexe Tabellen zu handhaben, indem sie robuste Ergebnisse durch effektive Analyse und Datenerfassung bietet. Sie ist besonders nützlich beim Umgang mit Tabellen mit komplexen Strukturen.

Wie kann ich mit der Tabellenerfassung mit IronOCR anfangen?

Um mit der Tabellenerfassung mit IronOCR zu beginnen, laden Sie die C#-Bibliothek herunter, bereiten Sie Ihr Dokument vor, aktivieren Sie die Tabellenerkennung, indem Sie die Eigenschaft ReadDataTables setzen, und verwenden Sie die Methode ReadDocumentAdvanced für komplexe Tabellen.

Welches zusätzliche Paket ist für die erweiterte Tabellenerfassung in IronOCR erforderlich?

Die erweiterte Tabellenerfassung in IronOCR erfordert das Paket `IronOcr.Extensions.AdvancedScan`, das spezifisch für Windows ist, um komplexe Tabellenstrukturen effektiv zu verwalten.

Wie kann ich extrahierte Tabellendaten mit IronOCR organisieren?

IronOCR bietet Hilfsmethoden, um extrahierte Tabellendaten nach Koordinaten zu organisieren, sodass Sie mehrere Tabellen verarbeiten und bestimmte Zeilen nach Index extrahieren können, um die Datenverwaltung zu verbessern.

Welche Metadaten sind in den extrahierten Tabellenzellen mit IronOCR enthalten?

Extrahierte Tabellenzellen mit IronOCR enthalten Metadaten wie X- und Y-Koordinaten, Zellendimensionen und den Textinhalt innerhalb jeder Zelle, was eine detaillierte Datenanalyse und -organisation ermöglicht.

Wie kann ich die Kompatibilität mit dem .NET Framework sicherstellen, wenn ich IronOCR zur Tabellenerfassung verwende?

Um die Kompatibilität mit dem .NET Framework sicherzustellen, stellen Sie sicher, dass Ihr Projekt auf x64-Architektur läuft und die 'Bevorzuge 32-Bit'-Option in der Projektkonfiguration deaktiviert ist, wenn Sie IronOCR für die Tabellenerfassung verwenden.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen
Rezensiert von
Jeff Fritz
Jeffrey T. Fritz
Principal Program Manager - .NET Community Team
Jeff ist außerdem Principal Program Manager für das .NET- und Visual Studio-Team. Er ist der ausführende Produzent der .NET Conf Virtual Conference Series und moderiert ‚Fritz and Friends‘, einen Livestream für Entwickler, der zweimal wöchentlich ausgestrahlt wird. Dort spricht er über Technik und schreibt gemeinsam mit den Zuschauern Code. Jeff schreibt Workshops, Präsentationen und plant Inhalte für die größten Microsoft-Entwicklerveranstaltungen, einschließlich Microsoft Build, Microsoft Ignite, .NET Conf und dem Microsoft MVP Summit.
Bereit anzufangen?
Nuget Downloads 5,044,537 | Version: 2025.11 gerade veröffentlicht