如何使用C#读取文档中的表格
IronOCR使C#开发者能够使用先进的机器学习模型从PDF和图像中的表格中提取数据,既能处理具有基本单元的简单表格,也能通过ReadDocumentAdvanced方法处理像合并单元格的发票等复杂结构。
使用普通 Tesseract 从表格中提取数据具有挑战性,因为文本通常位于单元格中,并且稀疏地分布在文档中。 不过,我们的库包括一个经过训练和微调的机器学习模型,可以准确地检测和提取表格数据。 无论是处理财务报告、库存清单还是发票数据,IronOCR 都能提供高效解析结构化数据的工具。
对于简单表格,依赖于使用标准OcrInput类的直接表格检测。 对于更复杂的结构,我们的独家ReadDocumentAdvanced方法提供可靠的结果,能够有效解析表格并传递数据。 这种先进的方法利用机器学习来理解表格布局、合并单元格和复杂的格式,而传统的 OCR 通常很难做到这一点。
几分钟即可开始使用 - 本示例展示了如何通过单次IronOCR调用使用ReadDocumentAdvanced从复杂文档中获取详细的表格单元数据。
它通过加载 PDF、应用高级表格检测并直接返回单元格信息列表来展示易用性。
-
1使用 IronOCR 安装 NuGet Package Manager
-
2复制并运行这段代码。
var input = new OcrInput(); input.LoadPdf("invoiceTable.pdf"); var cells = new IronTesseract().ReadDocumentAdvanced(input).Tables.First().CellInfos;Dim input As New OcrInput() input.LoadPdf("invoiceTable.pdf") Dim cells = (New IronTesseract()).ReadDocumentAdvanced(input).Tables.First().CellInfosDim input As New OcrInput() input.LoadPdf("invoiceTable.pdf") Dim cells = (New IronTesseract()).ReadDocumentAdvanced(input).Tables.First().CellInfos -
3部署到您的生产环境中进行测试
今天就用免费试用在您的项目中开始使用IronOCR
以下步骤指导您开始使用 IronOCR 读取表格:
最小工作流程(5 个步骤)
- 下载一个C#库以从表格中提取数据
- 准备图像和 PDF 文档以进行提取
- 将
ReadDataTables属性设置为 true 以启用表格检测 - 对于复杂表,请使用
ReadDocumentAdvanced方法。 - 提取这些方法检测到的数据
如何从简单表格中提取数据?
将ReadDataTables属性设置为true即可使用Tesseract进行表格检测。 这种方法适用于单元格边界清晰、无合并单元格的基本表格。 我创建了一个简单的表格PDF来测试此功能,您可以在此下载:'simple-table.pdf'。 可以使用此方法检测没有合并单元格的简单表格。 对于更复杂的表格,请参考下面介绍的方法。
标准表格检测方法对以下方面尤为有效:
- 电子表格输出
- 具有一致行/列结构的基本数据表
- 包含表格数据的报告
- 简单的库存清单
如果是一般的PDF OCR文本提取工作,此方法可与IronOCR的更广泛的文档处理功能集成。
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();
}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 rowImports 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如何读取复杂的发票表格?
在商业环境中,发票是比较常见的复杂表格之一。 发票是包含行和列数据的复杂表格,通常具有合并单元格、不同列宽和嵌套结构。 使用IronOCR,我们利用ReadDocumentAdvanced方法有效处理它们。 该过程包括扫描文档、识别表格结构和提取数据。 在本示例中,我们使用'invoiceTable.pdf'文件展示IronOCR如何从发票中检索所有信息。
ReadDocumentAdvanced 方法要求与基础 IronOCR 包一起安装 IronOcr.Extensions.AdvancedScan 包。 该扩展提供先进的机器学习功能,专门针对复杂的文档布局进行训练。
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;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;Imports IronOcr
Imports System.Linq
' Instantiate OCR engine
Dim ocr = New IronTesseract()
Using input As New OcrInput()
input.LoadPdf("invoiceTable.pdf")
' Perform OCR
Dim result = ocr.ReadDocumentAdvanced(input)
Dim cellList = result.Tables.First().CellInfos
End UsingImports IronOcr
Imports System.Linq
' Instantiate OCR engine
Dim ocr = New IronTesseract()
Using input As New OcrInput()
input.LoadPdf("invoiceTable.pdf")
' Perform OCR
Dim result = ocr.ReadDocumentAdvanced(input)
Dim cellList = result.Tables.First().CellInfos
End Using该方法将文档中的文本数据分为两类:一类有边框,另一类没有边框。 对于带边框的内容,库会根据表格的结构将其进一步细分为小节。 该方法擅长处理
- 具有不同描述的发票细列项目
- 多栏价格细目
- 发货和账单地址块
- 税金和总额计算部分
- 页眉和页脚信息
结果如下所示。 由于此方法侧重于边框所包含的信息,任何跨越多行的合并单元格都将被视为单个单元格。
提取的数据是什么样的?

如何组织和处理提取的表格单元?
在当前实现中,提取的单元格尚未正确组织。 但是,每个单元格都包含有价值的信息,例如 X 和 Y 坐标、尺寸等等。 利用这些数据,我们可以创建一个用于各种用途的辅助类。 单元信息包括
- 精确的 X/Y 坐标定位
- 宽度和高度尺寸
- 文本内容
- 信心评分
- 单元格关系
通过这些详细信息,您可以以编程方式重建表格结构,并应用自定义逻辑进行数据提取。 您还可以使用这些坐标定义特定区域,以便在后续操作中进行目标OCR处理。
以下是一些基本辅助方法:
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 ModuleImports 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表格提取的最佳实践
在 IronOCR 中进行表格提取时,请考虑以下最佳实践:
- 文档质量:分辨率越高的文档,结果越好。 对于扫描文件,请确保至少为 300 DPI。
- 预处理:对于质量较差或表格倾斜的文档,考虑在处理前使用IronOCR的图像校正功能。
- 性能:对于包含多个表格的大型文档,考虑使用多线程和异步支持以并行处理页面。
- 输出选项:提取表格数据后,您可以将结果导出为多种格式。 了解更多关于数据输出选项以及如何从您的处理文档中创建可搜索的PDF。
- 流处理:对于Web应用程序或在内存中处理文档的场景,考虑使用PDF流的OCR以避免文件系统操作。
总结
IronOCR 通过基于 Tesseract 的标准检测和先进的机器学习方法提供强大的表格提取功能。 标准方法适用于简单表格,而ReadDocumentAdvanced方法擅长处理复杂文档,如发票。 利用提供的辅助方法,您可以组织和处理提取的数据,以满足您的特定需求。
探索更多IronOCR功能以增强您的文档处理工作流,并在.NET应用程序中充分利用光学字符识别的潜力。
常见问题
如何使用C#从PDF或图像中提取表格数据?
IronOCR允许您使用高级机器学习模型在C#中从PDF和图像中提取表格数据。您可以使用ReadDocumentAdvanced方法准确检测和提取表格中的数据,包括具有复杂结构的表格。
IronOCR推荐使用什么方法来读取文档中的复杂表格?
对于读取复杂表格,IronOCR推荐使用ReadDocumentAdvanced方法。该方法利用机器学习处理复杂结构,如合并单元格的发票,比标准OCR方法提供更可靠和准确的结果。
IronOCR能在数据提取时处理表格中的合并单元格吗?
是的,IronOCR可以通过其ReadDocumentAdvanced方法有效地处理表格中的合并单元格。此高级功能使用机器学习来理解和提取包括合并或嵌套结构的复杂表格布局中的数据。
使用IronOCR提取简单表格数据的基本步骤是什么?
要使用IronOCR提取简单表格数据,您需要:下载库,准备文档,将ReadDataTables属性设置为true,并使用ReadDocumentAdvanced方法进行数据提取。该流程适用于具有清晰单元格边界的文档。
IronOCR如何确保在读取文档中的表格时的准确性?
IronOCR通过使用专为表格检测微调的高级机器学习模型确保准确性。ReadDocumentAdvanced方法可以准确检测表格布局并提取数据,即使在复杂文档如财务报告和发票中也是如此。
IronOCR需要什么额外的软件包来进行高级表格扫描?
对于高级表格扫描,您需要IronOcr.Extensions.AdvancedScan包。它增强了ReadDocumentAdvanced方法,以更复杂的机器学习能力处理复杂文档布局。
是否可以使用IronOCR根据坐标组织提取的表格单元格?
是的,IronOCR提供每个提取单元格的详细信息,包括其坐标。您可以使用此数据根据X和Y坐标对单元格进行编程排序,从而精确地重构表格结构。
使用IronOCR提取表格时推荐的文档质量是什么?
为了获得最佳效果,建议使用至少300 DPI分辨率的文档。更高质量的文档提高了OCR过程的准确性,并导致更好的表格提取结果。
IronOCR能否有效处理多页文档中的表格?
是的,IronOCR可以有效处理多页文档中的表格。它支持使用多线程和异步支持的并行处理,以高效处理大型文档中的多个表格。
IronOCR在提取表格数据后提供什么输出选项?
IronOCR在提取表格数据后提供多个输出选项,包括以各种格式导出结果和创建可搜索的PDF。探索其数据输出选项以满足您的需求。
Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。