如何使用C#讀取文件中的表格
IronOCR使C#開發者能夠透過高級機器學習模型從PDF和圖像中的表格提取數據,既能處理具有基本單元格的簡單表格,也能使用ReadDocumentAdvanced方法處理如合併單元格的發票等複雜結構。
使用純 Tesseract 從表格中萃取資料是一項挑戰,因為文字通常位於單元格中,並且稀疏地散佈在文件中。 然而,我們的資料庫包含一個經過訓練和微調的機器學習模型,可準確檢測和擷取表單資料。 無論是處理財務報告、庫存清單或發票資料,IronOCR 都能提供有效解析結構化資料的工具。
對於簡單表格,依賴使用標準OcrInput類別的直接表格偵測。 對於更複雜的結構,我們的獨家ReadDocumentAdvanced方法提供可靠的結果,能夠有效解析表格並提取數據。 這種先進的方法利用機器學習來理解表格佈局、合併的單元格以及複雜的格式,而傳統的 OCR 通常會在這些方面遇到困難。
在幾分鐘內即可上手使用 - 這個示例展示瞭如何通過用ReadDocumentAdvanced進行的一個IronOCR調用來獲取複雜文檔中的詳細表格單元格數據。
它透過載入 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。
- 流處理:對於網絡應用程式或處理內存文件的情境,考慮使用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。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。