Wie liest man sehr große Excel-Dateien in C# mit Forward-Only-Streaming
Eine Tabelle mit mehreren Hunderttausend Zeilen durchbricht den üblichen Ansatz. WorkBook.Load erstellt ein vollständiges In-Memory-Modell der Arbeitsmappe, was das Bearbeiten, Stylen, Formeln und den zufälligen Zugriff ermöglicht und warum ein 400-MB-Export Minuten dauern und mehrere Gigabyte verbrauchen kann, bevor der erste Wert gelesen wird.
IronXLs Forward-Only-Streaming-Reader, WorkBook.StreamRows, existiert für die Arbeiten, die nur die Werte benötigen. Es liefert eine Zeile nach der anderen direkt von der Festplatte, anstatt die Arbeitsmappe zu materialisieren, was den Speicher flach hält, egal wie viele Zeilen das Blatt enthält.
Wichtiger als die API selbst ist es, zu verstehen, wo die Grenze verläuft, denn ein Missverständnis dieser Grenze ist der Hauptgrund, warum das Feature falsch genutzt wird. StreamRows ist schreibgeschützt, nur XLSX und nur vorwärts: eine Schnellspur für die Massenwertextraktion. Bearbeitung, Styling, Formeln, Diagramme, zufälliger Zugriff und nicht-XLSX-Formate bleiben die Aufgabe von WorkBook.Load.
StreamRows nicht frei und schlagen beim Kompilieren fehl.Verweisen Sie StreamRows auf einen Dateipfad und enumerieren Sie das Ergebnis. Hinter den Kulissen liest die String-Pfad-Überladung die Teile der Arbeitsmappe faul von der Festplatte, und nur eine Zeile wird gleichzeitig materialisiert, was den Speicher flach über ein beliebig großes Blatt hält.
-
1Installieren Sie IronXL mit NuGet Package Manager
-
2Kopieren Sie diesen Codeausschnitt und führen Sie ihn aus.
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx")) Console.WriteLine(row[0]?.Text);For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx") Console.WriteLine(row(0)?.Text) NextFor Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx") Console.WriteLine(row(0)?.Text) Next -
3Bereitstellen zum Testen in Ihrer Live-Umgebung
Beginnen Sie noch heute, IronXL in Ihrem Projekt mit einer kostenlosen Testversion zu verwenden
Minimaler Arbeitsablauf (5 Schritte)
- Installieren oder aktualisieren Sie auf IronXL 2026.9.2 oder später und wenden Sie einen gültigen Lizenzschlüssel an
- Rufen Sie
WorkBook.GetSheetNames(path)auf, wenn das Zielblatt entdeckt werden muss - Rufen Sie
WorkBook.StreamRows(path, ...)mit einem Index des Blatts, einem Blattnamen oderStreamReadOptionsauf - Enumerieren Sie das zurückgegebene
IEnumerable<StreamRow>, wobei bei jedem Zellzugriff eine Nullprüfung durchgeführt wird - Prüfen Sie
StreamCell.Type, bevor SieValuelesen, und schreiben Sie Ergebnisse in Batches aus
Wie entscheide ich mich zwischen StreamRows und WorkBook.Load?
Der Unterschied ist eine Frage dessen, was der Auftrag benötigt, nicht nur der Dateigröße. Eine 50-MB-Datei, die eine Zellumgestaltung benötigt, gehört zu Load. Eine 500-MB-Datei, die drei Spalten in eine Datenbank schieben muss, gehört zu StreamRows.
Die Wahl zwischen dem Streaming-Reader und dem vollständigen Arbeitsmappenmodell
| Anforderung | StreamRows | WorkBook.Load |
|---|---|---|
| Massenwertextraktion, Importe, ETL, Validierung | Ja | Ja (langsamer) |
| Bearbeiten oder speichern | Nein | Ja |
| Stylen, Formatierungsobjekte | Nein | Ja |
| Formelausdrücke und -neuberechnung | Nein (nur gecachte Ergebnisse) | Ja |
| Zufälliger Zugriff auf beliebige Zellen | Nein (nur vorwärts) | Ja |
| XLS, CSV, TSV, verschlüsselte Arbeitsmappen | Nein | Ja |
| Diagramme und Bilder | Nein | Ja |
Die Lücke ist groß genug, um das Design eines Jobs zu ändern. Das Streamen aller 500.000 Zeilen eines 23,4-MB-Arbeitsmappe dauerte etwa sechs Sekunden und verbrauchte etwa 75 MB, wobei die erste Zeile innerhalb einer Viertelsekunde verfügbar war; WorkBook.Load auf derselben Datei ist in beiden Fällen deutlich schwerer. Hardware und Form der Arbeitsmappe verändern diese Zahlen, und Arbeitsmappen mit ungewöhnlich breiten Zeilen oder schweren geteilten String-Tabellen landen wieder anders. Der Leitfaden zur Datenladeleistung behandelt die gleichwertigen Kompromisse auf der Schreibseite.
Wie streame ich Zeilen aus einer Arbeitsmappe?
WorkBook.StreamRows ist eine statische Methode auf WorkBook. Geben Sie eine Quelle und ein Arbeitsblatt an, und enumerieren Sie das, was zurückkommt.
Eingabe
Eine halbe Million Zeilen mit Transaktionsdaten, acht Spalten breit, 23,4 MB auf der Festplatte. Excel öffnet es ohne Beschwerden; die Probleme beginnen, wenn der Code versucht, das Ganze in den Speicher zu ziehen.
using IronXL;
using System;
// The string path overload reads the workbook's parts lazily from disk.
// Nothing is loaded up front, and only one row exists in memory at a time.
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx"))
{
// Cells holds only the columns that actually have content on this row.
foreach (StreamCell cell in row.Cells)
{
Console.WriteLine("{0}{1} = {2}", cell.ColumnLetter, row.RowNumber + 1, cell.Text);
}
}using IronXL;
using System;
// The string path overload reads the workbook's parts lazily from disk.
// Nothing is loaded up front, and only one row exists in memory at a time.
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx"))
{
// Cells holds only the columns that actually have content on this row.
foreach (StreamCell cell in row.Cells)
{
Console.WriteLine("{0}{1} = {2}", cell.ColumnLetter, row.RowNumber + 1, cell.Text);
}
}Imports IronXL
Imports System
' The string path overload reads the workbook's parts lazily from disk.
' Nothing is loaded up front, and only one row exists in memory at a time.
For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx")
' Cells holds only the columns that actually have content on this row.
For Each cell As StreamCell In row.Cells
Console.WriteLine("{0}{1} = {2}", cell.ColumnLetter, row.RowNumber + 1, cell.Text)
Next
NextImports IronXL
Imports System
' The string path overload reads the workbook's parts lazily from disk.
' Nothing is loaded up front, and only one row exists in memory at a time.
For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx")
' Cells holds only the columns that actually have content on this row.
For Each cell As StreamCell In row.Cells
Console.WriteLine("{0}{1} = {2}", cell.ColumnLetter, row.RowNumber + 1, cell.Text)
Next
NextAusgabe
A1 = TxnId
B1 = Date
C1 = Sku
D1 = Description
E1 = Qty
F1 = UnitPrice
G1 = Region
H1 = Status
A2 = 1
B2 = 2026-01-01
C2 = SKU-079109
D2 = Item 0
E2 = 24
F2 = 8.62
G2 = North
H2 = OK
A3 = 2
B3 = 2026-02-02
C3 = SKU-011965
D3 = Item 1
E3 = 43
F3 = 460.94
G3 = South
H3 = PENDING
Eine Zeile pro Zelle, weil die Schleife row.Cells durchläuft, anstatt ein festes Set von Spalten. RowNumber ist nullbasiert, daher addiert das Beispiel eins, um die Ausgabe mit der eigenen Nummerierung von Excel abzugleichen. Beachten Sie, dass hier die Kopfzeile als normale Zeile ankommt: ohne StreamReadOptions bereitgestellt, kommen TxnId und Date als Zellwerte in Zeile 1 durch, anstatt die Spalten zu benennen.
Der Rückgabetyp ist IEnumerable<StreamRow>, und der entscheidende Unterschied ist, dass nichts gelesen wird, bis die Sequenz durchlaufen wird. Zeilen werden eine nach der anderen erzeugt, während die Schleife fortschreitet, sodass eine foreach über ein 500.000-Zeilen-Blatt eine einzelne Zeile im Speicher hält, anstatt einer halben Million. Die Konsequenz ist, dass die Sequenz einmalig und nur vorwärts ist: es gibt kein Zurück zu einer früheren Zeile und kein Indizieren in der Mitte einer Zeile. LINQ-Operatoren setzen sich im Allgemeinen dagegen, was bedeutet, dass .Take(1000) tausend Zeilen liest und dort stoppt.
Jeder StreamRow trägt nur die Zellen, die Inhalt haben, was weiter unten unter Arbeiten mit einem StreamRow behandelt wird.
Welchen Overload sollte ich verwenden?
Neun Überladungen decken drei Quellen und drei Arten der Benennung des Arbeitsblatts ab. Die Quelle ist die entscheidende Entscheidung, weil nur die string path-Überladungen faul von der Festplatte lesen. Die Stream- und byte[]-Überladungen müssen den dekomprimierten Inhalt des Pakets während des Lesevorgangs im Speicher halten.
Die neun StreamRows-Überladungen, alle die IEnumerable<StreamRow> zurückgeben
| Overload | Niedriger Speicherverbrauch |
|---|---|
StreamRows(string path, int sheetIndex = 0) | Ja |
StreamRows(string path, string sheetName) | Ja |
StreamRows(string path, StreamReadOptions options) | Ja |
StreamRows(Stream stream, int sheetIndex = 0) | Nein |
StreamRows(Stream stream, string sheetName) | Nein |
StreamRows(Stream stream, StreamReadOptions options) | Nein |
StreamRows(byte[] data, int sheetIndex = 0) | Nein |
StreamRows(byte[] data, string sheetName) | Nein |
StreamRows(byte[] data, StreamReadOptions options) | Nein |
Die Stream- und byte[]-Überladungen existieren für den Komfort, wenn eine Datei bereits im Speicher liegt, wie bei einem gepufferten Upload. Sie streamen immer noch Zeile für Zeile, sodass sie das vollständige Arbeitsmappenmodell vermeiden, aber der entpackte Inhalt bleibt für die gesamte Lesevorgang gespeichert. Erwarten Sie, dass es ungefähr das Zehnfache der Dateigröße auf der Festplatte läuft, sodass eine 23,4-MB-Arbeitsmappe etwas mehr als 200 MB hält, anstatt der von ihrer Dateigröße vorgeschlagenen Zahl. Verwenden Sie einen Dateipfad für die größten Dateien.
Alle drei geben identische Zeilen und Summen zurück; die Kosten sind Speicher, nicht Geschwindigkeit oder Genauigkeit
| Quelle | Verstrichen | Spitzenspeicher |
|---|---|---|
string path | 6,3 s | 75 MB |
Stream | 6,2 s | 309 MB |
byte[] | 6,3 s | 291 MB |
Die verstrichene Zeit ist effektiv identisch über die drei, was beachtet werden sollte: die falsche Überladung zu wählen, macht das Lesen nicht langsamer, sondern erschwert es. Ein Auftrag, der bequem im Speicher passt, wird den Unterschied überhaupt nicht bemerken, bis die Datei wächst oder das Containerlimit gesenkt wird.
Wie wähle ich ein Arbeitsblatt aus?
Die Blattwahl hat drei Formen: einen nullbasierten Index, einem genauen Blattnamen, der case-insensitiv abgeglichen wird, oder eine StreamReadOptions-Instanz. Ein unbekannter Blattname oder ein außerhalb des Bereichs liegender Index wirft ArgumentException.
using IronXL;
using System;
// 1. By zero-based index. Omitting the argument streams the first sheet.
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx", 2))
{
Console.WriteLine(row[0]?.Text);
}
// 2. By sheet name. Matching is case-insensitive, so "transactions" also works.
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx", "Transactions"))
{
Console.WriteLine(row[0]?.Text);
}
// 3. By StreamReadOptions, which is the only route to header support.
// SheetName takes precedence over SheetIndex whenever it is set.
StreamReadOptions options = new StreamReadOptions
{
SheetName = "Transactions",
HasHeaderRow = true
};
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx", options))
{
Console.WriteLine(row["Reference"]?.Text);
}
// An unknown sheet name or an out-of-range index throws ArgumentException.
try
{
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx", "NoSuchSheet"))
{
Console.WriteLine(row.RowNumber);
}
}
catch (ArgumentException ex)
{
Console.WriteLine("Sheet selection failed: {0}", ex.Message);
}using IronXL;
using System;
// 1. By zero-based index. Omitting the argument streams the first sheet.
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx", 2))
{
Console.WriteLine(row[0]?.Text);
}
// 2. By sheet name. Matching is case-insensitive, so "transactions" also works.
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx", "Transactions"))
{
Console.WriteLine(row[0]?.Text);
}
// 3. By StreamReadOptions, which is the only route to header support.
// SheetName takes precedence over SheetIndex whenever it is set.
StreamReadOptions options = new StreamReadOptions
{
SheetName = "Transactions",
HasHeaderRow = true
};
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx", options))
{
Console.WriteLine(row["Reference"]?.Text);
}
// An unknown sheet name or an out-of-range index throws ArgumentException.
try
{
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx", "NoSuchSheet"))
{
Console.WriteLine(row.RowNumber);
}
}
catch (ArgumentException ex)
{
Console.WriteLine("Sheet selection failed: {0}", ex.Message);
}Imports IronXL
Imports System
' 1. By zero-based index. Omitting the argument streams the first sheet.
For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx", 2)
Console.WriteLine(row(0)?.Text)
Next
' 2. By sheet name. Matching is case-insensitive, so "transactions" also works.
For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx", "Transactions")
Console.WriteLine(row(0)?.Text)
Next
' 3. By StreamReadOptions, which is the only route to header support.
' SheetName takes precedence over SheetIndex whenever it is set.
Dim options As New StreamReadOptions With {
.SheetName = "Transactions",
.HasHeaderRow = True
}
For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx", options)
Console.WriteLine(row("Reference")?.Text)
Next
' An unknown sheet name or an out-of-range index throws ArgumentException.
Try
For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx", "NoSuchSheet")
Console.WriteLine(row.RowNumber)
Next
Catch ex As ArgumentException
Console.WriteLine("Sheet selection failed: {0}", ex.Message)
End TryImports IronXL
Imports System
' 1. By zero-based index. Omitting the argument streams the first sheet.
For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx", 2)
Console.WriteLine(row(0)?.Text)
Next
' 2. By sheet name. Matching is case-insensitive, so "transactions" also works.
For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx", "Transactions")
Console.WriteLine(row(0)?.Text)
Next
' 3. By StreamReadOptions, which is the only route to header support.
' SheetName takes precedence over SheetIndex whenever it is set.
Dim options As New StreamReadOptions With {
.SheetName = "Transactions",
.HasHeaderRow = True
}
For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx", options)
Console.WriteLine(row("Reference")?.Text)
Next
' An unknown sheet name or an out-of-range index throws ArgumentException.
Try
For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx", "NoSuchSheet")
Console.WriteLine(row.RowNumber)
Next
Catch ex As ArgumentException
Console.WriteLine("Sheet selection failed: {0}", ex.Message)
End TryKeine Blattargumente zu übergeben streamt das erste Blatt, da sheetIndex standardmäßig auf 0 zurückgreift. StreamReadOptions ist der einzige Weg, der Kopfzeilen unterstützt, also greifen Sie darauf zurück, sobald Spalten Namen benötigen.
Wie finde ich Blätter vor dem Streamen heraus?
WorkBook.GetSheetNames listet jedes Blatt in der Reihenfolge der Arbeitsmappe auf, ohne den Inhalt der Arbeitsmappe zu laden. Es liest nur die Teileliste der Arbeitsmappe, sodass es auch bei einer sehr großen Datei kostengünstig bleibt: etwa eine Viertelsekunde auf der 23,4-MB, 500.000-Zeilen-Arbeitsmappe, was dieselbe Zeit ist, die es auf einer Datei von wenigen Kilobytes dauert. Das macht es zum natürlichen ersten Anruf für eine Datei, die aus einem externen System kommt, dessen Layout im Voraus nicht bekannt ist.
Die drei GetSheetNames-Überladungen, die alle IReadOnlyList<string> zurückgeben
| Overload | Quelle |
|---|---|
GetSheetNames(string path) | Eine Datei auf der Festplatte |
GetSheetNames(Stream stream) | Ein geöffneter Stream |
GetSheetNames(byte[] data) | Ein In-Memory-Puffer |
Die Position in der zurückgegebenen Liste entspricht dem Blattindex, den StreamRows akzeptiert, sodass die beiden APIs direkt aufeinander abgestimmt sind: Index 2 in dieser Liste ist das Blatt, das StreamRows(path, 2) liest.
using IronXL;
using System;
using System.Collections.Generic;
// GetSheetNames reads only the workbook's part list, not sheet data, so it is cheap
// even on a very large file. List position equals the sheet index StreamRows accepts.
IReadOnlyList<string> sheetNames = WorkBook.GetSheetNames("large-export.xlsx");
for (int i = 0; i < sheetNames.Count; i++)
{
Console.WriteLine("[{0}] {1}", i, sheetNames[i]);
}
// Stream by exact sheet name. Matching is case-insensitive.
// An unknown name, or an out-of-range index, throws ArgumentException.
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx", "Transactions"))
{
StreamCell reference = row[0];
if (reference is not null)
{
Console.WriteLine(reference.Text);
}
}using IronXL;
using System;
using System.Collections.Generic;
// GetSheetNames reads only the workbook's part list, not sheet data, so it is cheap
// even on a very large file. List position equals the sheet index StreamRows accepts.
IReadOnlyList<string> sheetNames = WorkBook.GetSheetNames("large-export.xlsx");
for (int i = 0; i < sheetNames.Count; i++)
{
Console.WriteLine("[{0}] {1}", i, sheetNames[i]);
}
// Stream by exact sheet name. Matching is case-insensitive.
// An unknown name, or an out-of-range index, throws ArgumentException.
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx", "Transactions"))
{
StreamCell reference = row[0];
if (reference is not null)
{
Console.WriteLine(reference.Text);
}
}Imports IronXL
Imports System
Imports System.Collections.Generic
' GetSheetNames reads only the workbook's part list, not sheet data, so it is cheap
' even on a very large file. List position equals the sheet index StreamRows accepts.
Dim sheetNames As IReadOnlyList(Of String) = WorkBook.GetSheetNames("large-export.xlsx")
For i As Integer = 0 To sheetNames.Count - 1
Console.WriteLine("[{0}] {1}", i, sheetNames(i))
Next
' Stream by exact sheet name. Matching is case-insensitive.
' An unknown name, or an out-of-range index, throws ArgumentException.
For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx", "Transactions")
Dim reference As StreamCell = row(0)
If reference IsNot Nothing Then
Console.WriteLine(reference.Text)
End If
NextImports IronXL
Imports System
Imports System.Collections.Generic
' GetSheetNames reads only the workbook's part list, not sheet data, so it is cheap
' even on a very large file. List position equals the sheet index StreamRows accepts.
Dim sheetNames As IReadOnlyList(Of String) = WorkBook.GetSheetNames("large-export.xlsx")
For i As Integer = 0 To sheetNames.Count - 1
Console.WriteLine("[{0}] {1}", i, sheetNames(i))
Next
' Stream by exact sheet name. Matching is case-insensitive.
' An unknown name, or an out-of-range index, throws ArgumentException.
For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx", "Transactions")
Dim reference As StreamCell = row(0)
If reference IsNot Nothing Then
Console.WriteLine(reference.Text)
End If
NextWie lese ich Zeilen nach Spaltenname?
Das Setzen von HasHeaderRow benennt die Spalten und lässt Zeilen nach Kopfzeilenname lesen. Die Kopfzeile wird zur Benennung genutzt und nicht als Daten geliefert, und alle Zeilen vor HeaderRowIndex werden übersprungen, was den üblichen Fall einer Überschrift oder eines Vorworts oberhalb der realen Kopfzeile behandelt.
using IronXL;
using System;
// This source file carries a title and a blank spacer above the real header,
// so the header sits on Excel row 3, which is HeaderRowIndex 2 (zero-based).
StreamReadOptions options = new StreamReadOptions
{
SheetName = "Transactions",
HasHeaderRow = true,
HeaderRowIndex = 2
};
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx", options))
{
// The header row is consumed to name columns and is never yielded as data.
// Rows before HeaderRowIndex are skipped.
// Named access requires HasHeaderRow; without it the string indexer throws
// InvalidOperationException.
StreamCell reference = row["Reference"];
StreamCell amount = row["Amount"];
// Both the sparse-row case and a blank cell produce null, so null-check before use.
if (reference is null || amount is null)
{
continue;
}
Console.WriteLine("{0}: {1}", reference.Text, amount.Text);
}using IronXL;
using System;
// This source file carries a title and a blank spacer above the real header,
// so the header sits on Excel row 3, which is HeaderRowIndex 2 (zero-based).
StreamReadOptions options = new StreamReadOptions
{
SheetName = "Transactions",
HasHeaderRow = true,
HeaderRowIndex = 2
};
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx", options))
{
// The header row is consumed to name columns and is never yielded as data.
// Rows before HeaderRowIndex are skipped.
// Named access requires HasHeaderRow; without it the string indexer throws
// InvalidOperationException.
StreamCell reference = row["Reference"];
StreamCell amount = row["Amount"];
// Both the sparse-row case and a blank cell produce null, so null-check before use.
if (reference is null || amount is null)
{
continue;
}
Console.WriteLine("{0}: {1}", reference.Text, amount.Text);
}Imports IronXL
Imports System
' This source file carries a title and a blank spacer above the real header,
' so the header sits on Excel row 3, which is HeaderRowIndex 2 (zero-based).
Dim options As New StreamReadOptions With {
.SheetName = "Transactions",
.HasHeaderRow = True,
.HeaderRowIndex = 2
}
For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx", options)
' The header row is consumed to name columns and is never yielded as data.
' Rows before HeaderRowIndex are skipped.
' Named access requires HasHeaderRow; without it the string indexer throws
' InvalidOperationException.
Dim reference As StreamCell = row("Reference")
Dim amount As StreamCell = row("Amount")
' Both the sparse-row case and a blank cell produce null, so null-check before use.
If reference Is Nothing OrElse amount Is Nothing Then
Continue For
End If
Console.WriteLine("{0}: {1}", reference.Text, amount.Text)
NextImports IronXL
Imports System
' This source file carries a title and a blank spacer above the real header,
' so the header sits on Excel row 3, which is HeaderRowIndex 2 (zero-based).
Dim options As New StreamReadOptions With {
.SheetName = "Transactions",
.HasHeaderRow = True,
.HeaderRowIndex = 2
}
For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx", options)
' The header row is consumed to name columns and is never yielded as data.
' Rows before HeaderRowIndex are skipped.
' Named access requires HasHeaderRow; without it the string indexer throws
' InvalidOperationException.
Dim reference As StreamCell = row("Reference")
Dim amount As StreamCell = row("Amount")
' Both the sparse-row case and a blank cell produce null, so null-check before use.
If reference Is Nothing OrElse amount Is Nothing Then
Continue For
End If
Console.WriteLine("{0}: {1}", reference.Text, amount.Text)
NextHasHeaderRow. Ohne sie werfen der String-Indexer und TryGetCell beide InvalidOperationException.Die Kopfzeilenbehandlung ist absichtlich streng. Wenn das Blatt keine Zeile bei oder vor der konfigurierten HeaderRowIndex hat, wirft die Aufzählung InvalidOperationException mit der Meldung "Kopfzeile nicht gefunden" und wirft, sobald eine Datenzeile den Kopfzeilenindex überschreitet. Dies stellt sicher, dass ein Verbraucher, der zu Take oder einer frühen break greift, die Fehlkonfiguration sofort sieht, anstatt stillschweigend nichts zu lesen.
Das Abgleichen von Spaltennamen ist case-insensitiv und trimmt umgebende Leerzeichen. Doppelte Kopfzeilennamen werden an der ersten, linken passenden Spalte aufgelöst.
Was konfiguriert StreamReadOptions?
StreamReadOptions Eigenschaften, festgelegt durch den Objektinitialisierer
| Eigenschaft | Typ | Default | Verhalten |
|---|---|---|---|
SheetIndex | int | 0 | Nullbasierter Arbeitsblattindex. Wird ignoriert, wenn SheetName gesetzt ist |
SheetName | string | null | Arbeitsblattname, case-insensitiv abgeglichen. Geht vor SheetIndex |
HasHeaderRow | bool | false | Wenn wahr, benennt die Zeile bei HeaderRowIndex die Spalten und wird nicht als Daten ausgegeben |
HeaderRowIndex | int | 0 | Nullbasierte Blattzeile, die die Kopfzeile hält. Zeilen davor werden übersprungen |
Wie gehe ich mit optionalen Spalten um?
Die beiden benannten Zugriffsmethoden unterscheiden sich darin, wie sie eine Spalte behandeln, die nicht in der Kopfzeile vorhanden ist, und die falsche zu wählen, verwandelt eine erträgliche Quelldatei in einen Absturz. Der String-Indexer wirft ArgumentException; TryGetCell gibt false zurück.
using IronXL;
using System;
StreamReadOptions options = new StreamReadOptions
{
SheetIndex = 0,
HasHeaderRow = true
};
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx", options))
{
// The string indexer throws ArgumentException when the column name is absent
// from the header. TryGetCell returns false instead, which makes it the correct
// choice for a column that may not exist in every source file.
if (row.TryGetCell("CostCentre", out StreamCell costCentre) && costCentre is not null)
{
Console.WriteLine("Cost centre: {0}", costCentre.Text);
}
else
{
Console.WriteLine("Cost centre: not supplied");
}
// Header is positioned by column, so Header[i] lines up with column i.
// A blank header column is null.
for (int i = 0; i < row.Header.Count; i++)
{
string columnName = row.Header[i];
if (string.IsNullOrEmpty(columnName))
{
continue;
}
StreamCell cell = row[i];
Console.WriteLine(" {0} ({1}) = {2}", columnName, cell?.ColumnLetter, cell?.Text);
}
}using IronXL;
using System;
StreamReadOptions options = new StreamReadOptions
{
SheetIndex = 0,
HasHeaderRow = true
};
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx", options))
{
// The string indexer throws ArgumentException when the column name is absent
// from the header. TryGetCell returns false instead, which makes it the correct
// choice for a column that may not exist in every source file.
if (row.TryGetCell("CostCentre", out StreamCell costCentre) && costCentre is not null)
{
Console.WriteLine("Cost centre: {0}", costCentre.Text);
}
else
{
Console.WriteLine("Cost centre: not supplied");
}
// Header is positioned by column, so Header[i] lines up with column i.
// A blank header column is null.
for (int i = 0; i < row.Header.Count; i++)
{
string columnName = row.Header[i];
if (string.IsNullOrEmpty(columnName))
{
continue;
}
StreamCell cell = row[i];
Console.WriteLine(" {0} ({1}) = {2}", columnName, cell?.ColumnLetter, cell?.Text);
}
}Imports IronXL
Imports System
Dim options As New StreamReadOptions With {
.SheetIndex = 0,
.HasHeaderRow = True
}
For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx", options)
' The string indexer throws ArgumentException when the column name is absent
' from the header. TryGetCell returns false instead, which makes it the correct
' choice for a column that may not exist in every source file.
Dim costCentre As StreamCell = Nothing
If row.TryGetCell("CostCentre", costCentre) And costCentre IsNot Nothing Then
Console.WriteLine("Cost centre: {0}", costCentre.Text)
Else
Console.WriteLine("Cost centre: not supplied")
End If
' Header is positioned by column, so Header[i] lines up with column i.
' A blank header column is null.
For i As Integer = 0 To row.Header.Count - 1
Dim columnName As String = row.Header(i)
If String.IsNullOrEmpty(columnName) Then
Continue For
End If
Dim cell As StreamCell = row(i)
Console.WriteLine(" {0} ({1}) = {2}", columnName, cell?.ColumnLetter, cell?.Text)
Next
NextImports IronXL
Imports System
Dim options As New StreamReadOptions With {
.SheetIndex = 0,
.HasHeaderRow = True
}
For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx", options)
' The string indexer throws ArgumentException when the column name is absent
' from the header. TryGetCell returns false instead, which makes it the correct
' choice for a column that may not exist in every source file.
Dim costCentre As StreamCell = Nothing
If row.TryGetCell("CostCentre", costCentre) And costCentre IsNot Nothing Then
Console.WriteLine("Cost centre: {0}", costCentre.Text)
Else
Console.WriteLine("Cost centre: not supplied")
End If
' Header is positioned by column, so Header[i] lines up with column i.
' A blank header column is null.
For i As Integer = 0 To row.Header.Count - 1
Dim columnName As String = row.Header(i)
If String.IsNullOrEmpty(columnName) Then
Continue For
End If
Dim cell As StreamCell = row(i)
Console.WriteLine(" {0} ({1}) = {2}", columnName, cell?.ColumnLetter, cell?.Text)
Next
NextTryGetCell beantwortet eine engere Frage als es zunächst erscheint: Es berichtet, ob der Kopfzeile den Spaltennamen enthält, nicht, ob diese bestimmte Zeile dort einen Wert hat. Eine Zeile mit einem spärlichen Spalt in einer bekannten Spalte gibt true mit einer null-Zelle zurück, sodass beim Auslesen immer noch eine Nullprüfung erforderlich ist. Verwenden Sie TryGetCell für jede Spalte, die in einigen Quelldateien fehlen kann, und den String-Indexer nur dort, wo die Spalte garantiert ist.
Wie arbeite ich mit einem StreamRow?
Ein StreamRow ist eine Zeile, die während der Enumeration erzeugt wird. Es zeigt seine Position, die Zellen, die es tatsächlich enthält, sowie sowohl den positionsbezogenen als auch den benannten Lookup.
using IronXL;
using System;
StreamReadOptions options = new StreamReadOptions
{
SheetName = "Transactions",
HasHeaderRow = true
};
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx", options))
{
// RowNumber is zero-based, so Excel row 1 is RowNumber 0.
// With a header consumed, the first data row keeps its real sheet position.
Console.WriteLine("Sheet row {0}, {1} populated cells", row.RowNumber, row.Cells.Count);
// Index access. Rows are sparse, so a column with no content returns null
// rather than a blank cell object.
StreamCell firstColumn = row[0];
Console.WriteLine(" column A: {0}", firstColumn?.Text ?? "(empty)");
// Name access. Requires HasHeaderRow, and throws ArgumentException if the
// header has no such column. Matching is case-insensitive and trims whitespace.
StreamCell reference = row["Reference"];
Console.WriteLine(" Reference: {0}", reference?.Text ?? "(empty)");
// Header is positioned by column: Header[i] names column i.
// A column with a blank header cell is null.
for (int i = 0; i < row.Header.Count; i++)
{
string name = row.Header[i];
Console.WriteLine(" column {0} is named {1}", i, name ?? "(unnamed)");
}
}using IronXL;
using System;
StreamReadOptions options = new StreamReadOptions
{
SheetName = "Transactions",
HasHeaderRow = true
};
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx", options))
{
// RowNumber is zero-based, so Excel row 1 is RowNumber 0.
// With a header consumed, the first data row keeps its real sheet position.
Console.WriteLine("Sheet row {0}, {1} populated cells", row.RowNumber, row.Cells.Count);
// Index access. Rows are sparse, so a column with no content returns null
// rather than a blank cell object.
StreamCell firstColumn = row[0];
Console.WriteLine(" column A: {0}", firstColumn?.Text ?? "(empty)");
// Name access. Requires HasHeaderRow, and throws ArgumentException if the
// header has no such column. Matching is case-insensitive and trims whitespace.
StreamCell reference = row["Reference"];
Console.WriteLine(" Reference: {0}", reference?.Text ?? "(empty)");
// Header is positioned by column: Header[i] names column i.
// A column with a blank header cell is null.
for (int i = 0; i < row.Header.Count; i++)
{
string name = row.Header[i];
Console.WriteLine(" column {0} is named {1}", i, name ?? "(unnamed)");
}
}Imports IronXL
Imports System
Dim options As New StreamReadOptions With {
.SheetName = "Transactions",
.HasHeaderRow = True
}
For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx", options)
' RowNumber is zero-based, so Excel row 1 is RowNumber 0.
' With a header consumed, the first data row keeps its real sheet position.
Console.WriteLine("Sheet row {0}, {1} populated cells", row.RowNumber, row.Cells.Count)
' Index access. Rows are sparse, so a column with no content returns null
' rather than a blank cell object.
Dim firstColumn As StreamCell = row(0)
Console.WriteLine(" column A: {0}", If(firstColumn?.Text, "(empty)"))
' Name access. Requires HasHeaderRow, and throws ArgumentException if the
' header has no such column. Matching is case-insensitive and trims whitespace.
Dim reference As StreamCell = row("Reference")
Console.WriteLine(" Reference: {0}", If(reference?.Text, "(empty)"))
' Header is positioned by column: Header[i] names column i.
' A column with a blank header cell is null.
For i As Integer = 0 To row.Header.Count - 1
Dim name As String = row.Header(i)
Console.WriteLine(" column {0} is named {1}", i, If(name, "(unnamed)"))
Next
NextImports IronXL
Imports System
Dim options As New StreamReadOptions With {
.SheetName = "Transactions",
.HasHeaderRow = True
}
For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx", options)
' RowNumber is zero-based, so Excel row 1 is RowNumber 0.
' With a header consumed, the first data row keeps its real sheet position.
Console.WriteLine("Sheet row {0}, {1} populated cells", row.RowNumber, row.Cells.Count)
' Index access. Rows are sparse, so a column with no content returns null
' rather than a blank cell object.
Dim firstColumn As StreamCell = row(0)
Console.WriteLine(" column A: {0}", If(firstColumn?.Text, "(empty)"))
' Name access. Requires HasHeaderRow, and throws ArgumentException if the
' header has no such column. Matching is case-insensitive and trims whitespace.
Dim reference As StreamCell = row("Reference")
Console.WriteLine(" Reference: {0}", If(reference?.Text, "(empty)"))
' Header is positioned by column: Header[i] names column i.
' A column with a blank header cell is null.
For i As Integer = 0 To row.Header.Count - 1
Dim name As String = row.Header(i)
Console.WriteLine(" column {0} is named {1}", i, If(name, "(unnamed)"))
Next
NextStreamRow Mitglieder, mit sowohl positionsbezogenen als auch benannten Zugriff
| Mitglied | Typ | Verhalten |
|---|---|---|
RowNumber | int | Null basiert. Excel-Zeile 1 ist RowNumber 0 |
Cells | IReadOnlyList<StreamCell> | Spärlich. Nur Spalten mit Inhalt sind vorhanden |
Header | IReadOnlyList<string> | Spaltennamen, die nach Spalten positioniert sind, sodass Header[i] Spalte i benennt. Eine leere Kopfzeilenspalte ist null, und Header selbst ist null, wenn keine Kopfzeile konfiguriert wurde |
this[int columnIndex] | StreamCell | Zelle an einem nullbasierten Spaltenindex, oder null für einen spärlichen Spalt |
this[string columnName] | StreamCell | Zelle unter einer benannten Kopfzeilenspalte. Wirft ArgumentException, wenn der Name fehlt |
TryGetCell(string, out StreamCell) | bool | true, wenn die Kopfzeile den Namen enthält, false, wenn nicht |
Header ist null, es sei denn, StreamReadOptions.HasHeaderRow wurde gesetzt. Schützen Sie es vor dem Iterieren, sonst verfehlt die Schleife eine Nullliste.Sparsamkeit ist die Eigenschaft, die den aufrufenden Code formt. Eine Zeile ist kein fixes Breitenformat: Ein Blatt mit den Spalten A bis F erzeugt Zeilen, die drei Zellen enthalten, wo drei Spalten ausgefüllt wurden, und der positionsbasierte Indexer gibt null für die Lücken zurück. RowNumber, das nullbasiert ist, ist konsistent mit dem Rest von IronXL, wo numerische Indexer nullbasiert sind, während A1-String-Adressen dies nicht sind.
Wie lese ich typisierte Werte von einem StreamCell?
Ein StreamCell ist ein unveränderlicher Schnappschuss einer Zelle. Anders als ein normales Cell wird es nicht von der Arbeitsmappe unterstützt und kann nicht verwendet werden, um einen Wert zurückzuschreiben.
using IronXL;
using System;
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx", "Transactions"))
{
StreamCell cell = row[1];
// Sparse gap: no cell at this column on this row.
if (cell is null)
{
continue;
}
// Position: zero-based index, plus the spreadsheet column letter.
Console.WriteLine("Column {0} (letter {1})", cell.ColumnIndex, cell.ColumnLetter);
// Type classifies the value. For a formula cell it reports the type of the
// cached result, never a "formula" type.
Console.WriteLine(" Type: {0}", cell.Type);
// IsFormula is how formula-ness is exposed. The expression itself is not
// available from the streaming reader, only the cached result.
Console.WriteLine(" IsFormula: {0}", cell.IsFormula);
// Value is the raw typed value, and is null for a blank cell.
Console.WriteLine(" Value: {0}", cell.Value ?? "(null)");
// Text is the formatted display text, which is what Excel shows in the cell.
Console.WriteLine(" Text: {0}", cell.Text);
}using IronXL;
using System;
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx", "Transactions"))
{
StreamCell cell = row[1];
// Sparse gap: no cell at this column on this row.
if (cell is null)
{
continue;
}
// Position: zero-based index, plus the spreadsheet column letter.
Console.WriteLine("Column {0} (letter {1})", cell.ColumnIndex, cell.ColumnLetter);
// Type classifies the value. For a formula cell it reports the type of the
// cached result, never a "formula" type.
Console.WriteLine(" Type: {0}", cell.Type);
// IsFormula is how formula-ness is exposed. The expression itself is not
// available from the streaming reader, only the cached result.
Console.WriteLine(" IsFormula: {0}", cell.IsFormula);
// Value is the raw typed value, and is null for a blank cell.
Console.WriteLine(" Value: {0}", cell.Value ?? "(null)");
// Text is the formatted display text, which is what Excel shows in the cell.
Console.WriteLine(" Text: {0}", cell.Text);
}Imports IronXL
Imports System
For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx", "Transactions")
Dim cell As StreamCell = row(1)
' Sparse gap: no cell at this column on this row.
If cell Is Nothing Then
Continue For
End If
' Position: zero-based index, plus the spreadsheet column letter.
Console.WriteLine("Column {0} (letter {1})", cell.ColumnIndex, cell.ColumnLetter)
' Type classifies the value. For a formula cell it reports the type of the
' cached result, never a "formula" type.
Console.WriteLine(" Type: {0}", cell.Type)
' IsFormula is how formula-ness is exposed. The expression itself is not
' available from the streaming reader, only the cached result.
Console.WriteLine(" IsFormula: {0}", cell.IsFormula)
' Value is the raw typed value, and is null for a blank cell.
Console.WriteLine(" Value: {0}", If(cell.Value, "(null)"))
' Text is the formatted display text, which is what Excel shows in the cell.
Console.WriteLine(" Text: {0}", cell.Text)
NextImports IronXL
Imports System
For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx", "Transactions")
Dim cell As StreamCell = row(1)
' Sparse gap: no cell at this column on this row.
If cell Is Nothing Then
Continue For
End If
' Position: zero-based index, plus the spreadsheet column letter.
Console.WriteLine("Column {0} (letter {1})", cell.ColumnIndex, cell.ColumnLetter)
' Type classifies the value. For a formula cell it reports the type of the
' cached result, never a "formula" type.
Console.WriteLine(" Type: {0}", cell.Type)
' IsFormula is how formula-ness is exposed. The expression itself is not
' available from the streaming reader, only the cached result.
Console.WriteLine(" IsFormula: {0}", cell.IsFormula)
' Value is the raw typed value, and is null for a blank cell.
Console.WriteLine(" Value: {0}", If(cell.Value, "(null)"))
' Text is the formatted display text, which is what Excel shows in the cell.
Console.WriteLine(" Text: {0}", cell.Text)
NextStreamCell Mitglieder, die Position, Typ und Wert abdecken
| Mitglied | Typ | Verhalten |
|---|---|---|
ColumnIndex | int | Nullbasierter Spaltenindex |
ColumnLetter | string | Tabellenkalkulationsspaltenbuchstaben, zum Beispiel "A", "C" oder "AA" |
Type | StreamCellType | Die Art des gehaltenen Werts. Bei einer Formelezelle der Typ des gecachten Ergebnisses |
Value | object | Der rohe typisierte Wert. null für eine leere Zelle |
Text | string | Der formatierte Anzeigeinhalt, wie ihn Excel zeigt |
IsFormula | bool | true, wenn die Zelle eine Formel enthält |
Value ist eingepackt, das bedeutet, dass die Umwandlung sich aus Type ergibt:
Numbergibt einedoubleStringgibt einestringBooleangibt eineboolDategibt eineDateTimeBlankgibtnull
Das Überprüfen von Type, bevor auf Value zugegriffen wird, macht den Unterschied zwischen einem Import, der mit realen Daten überlebt, und einem, der bei Zeile 40.000 wirft.
using IronXL;
using System;
using System.Globalization;
StreamReadOptions options = new StreamReadOptions
{
SheetName = "Transactions",
HasHeaderRow = true
};
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx", options))
{
StreamCell amount = row["Amount"];
// Sparse rows and blank cells both yield null. Check before touching Type or Value.
if (amount is null || amount.Type == StreamCellType.Blank)
{
continue;
}
// A formula cell reports IsFormula true, and Type reports the real type of the
// cached result. The formula expression itself is not exposed, and nothing is
// recalculated, which is why StreamCellType has no Formula member.
if (amount.IsFormula)
{
Console.WriteLine("Row {0} column {1} is a cached formula result.",
row.RowNumber, amount.ColumnLetter);
}
switch (amount.Type)
{
case StreamCellType.Number:
// Convert rather than casting directly: the boxed numeric type is not
// guaranteed to be the one you expect.
decimal value = Convert.ToDecimal(amount.Value, CultureInfo.InvariantCulture);
Console.WriteLine("Amount: {0}", value);
break;
case StreamCellType.Date:
// Date cells honour the workbook's date system, including 1904-based
// workbooks produced by Excel for Mac.
if (amount.Value is DateTime date)
{
Console.WriteLine("Date: {0:yyyy-MM-dd}", date);
}
break;
case StreamCellType.Boolean:
Console.WriteLine("Flag: {0}", Convert.ToBoolean(amount.Value));
break;
case StreamCellType.Error:
Console.WriteLine("Row {0} contains an error value.", row.RowNumber);
break;
default:
// Falls through to the formatted display text for String and anything else.
Console.WriteLine("Text: {0}", amount.Text);
break;
}
}using IronXL;
using System;
using System.Globalization;
StreamReadOptions options = new StreamReadOptions
{
SheetName = "Transactions",
HasHeaderRow = true
};
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx", options))
{
StreamCell amount = row["Amount"];
// Sparse rows and blank cells both yield null. Check before touching Type or Value.
if (amount is null || amount.Type == StreamCellType.Blank)
{
continue;
}
// A formula cell reports IsFormula true, and Type reports the real type of the
// cached result. The formula expression itself is not exposed, and nothing is
// recalculated, which is why StreamCellType has no Formula member.
if (amount.IsFormula)
{
Console.WriteLine("Row {0} column {1} is a cached formula result.",
row.RowNumber, amount.ColumnLetter);
}
switch (amount.Type)
{
case StreamCellType.Number:
// Convert rather than casting directly: the boxed numeric type is not
// guaranteed to be the one you expect.
decimal value = Convert.ToDecimal(amount.Value, CultureInfo.InvariantCulture);
Console.WriteLine("Amount: {0}", value);
break;
case StreamCellType.Date:
// Date cells honour the workbook's date system, including 1904-based
// workbooks produced by Excel for Mac.
if (amount.Value is DateTime date)
{
Console.WriteLine("Date: {0:yyyy-MM-dd}", date);
}
break;
case StreamCellType.Boolean:
Console.WriteLine("Flag: {0}", Convert.ToBoolean(amount.Value));
break;
case StreamCellType.Error:
Console.WriteLine("Row {0} contains an error value.", row.RowNumber);
break;
default:
// Falls through to the formatted display text for String and anything else.
Console.WriteLine("Text: {0}", amount.Text);
break;
}
}Imports IronXL
Imports System
Imports System.Globalization
Dim options As New StreamReadOptions With {
.SheetName = "Transactions",
.HasHeaderRow = True
}
For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx", options)
Dim amount As StreamCell = row("Amount")
' Sparse rows and blank cells both yield null. Check before touching Type or Value.
If amount Is Nothing OrElse amount.Type = StreamCellType.Blank Then
Continue For
End If
' A formula cell reports IsFormula true, and Type reports the real type of the
' cached result. The formula expression itself is not exposed, and nothing is
' recalculated, which is why StreamCellType has no Formula member.
If amount.IsFormula Then
Console.WriteLine("Row {0} column {1} is a cached formula result.",
row.RowNumber, amount.ColumnLetter)
End If
Select Case amount.Type
Case StreamCellType.Number
' Convert rather than casting directly: the boxed numeric type is not
' guaranteed to be the one you expect.
Dim value As Decimal = Convert.ToDecimal(amount.Value, CultureInfo.InvariantCulture)
Console.WriteLine("Amount: {0}", value)
Case StreamCellType.Date
' Date cells honour the workbook's date system, including 1904-based
' workbooks produced by Excel for Mac.
If TypeOf amount.Value Is DateTime Then
Dim [date] As DateTime = DirectCast(amount.Value, DateTime)
Console.WriteLine("Date: {0:yyyy-MM-dd}", [date])
End If
Case StreamCellType.Boolean
Console.WriteLine("Flag: {0}", Convert.ToBoolean(amount.Value))
Case StreamCellType.Error
Console.WriteLine("Row {0} contains an error value.", row.RowNumber)
Case Else
' Falls through to the formatted display text for String and anything else.
Console.WriteLine("Text: {0}", amount.Text)
End Select
NextImports IronXL
Imports System
Imports System.Globalization
Dim options As New StreamReadOptions With {
.SheetName = "Transactions",
.HasHeaderRow = True
}
For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx", options)
Dim amount As StreamCell = row("Amount")
' Sparse rows and blank cells both yield null. Check before touching Type or Value.
If amount Is Nothing OrElse amount.Type = StreamCellType.Blank Then
Continue For
End If
' A formula cell reports IsFormula true, and Type reports the real type of the
' cached result. The formula expression itself is not exposed, and nothing is
' recalculated, which is why StreamCellType has no Formula member.
If amount.IsFormula Then
Console.WriteLine("Row {0} column {1} is a cached formula result.",
row.RowNumber, amount.ColumnLetter)
End If
Select Case amount.Type
Case StreamCellType.Number
' Convert rather than casting directly: the boxed numeric type is not
' guaranteed to be the one you expect.
Dim value As Decimal = Convert.ToDecimal(amount.Value, CultureInfo.InvariantCulture)
Console.WriteLine("Amount: {0}", value)
Case StreamCellType.Date
' Date cells honour the workbook's date system, including 1904-based
' workbooks produced by Excel for Mac.
If TypeOf amount.Value Is DateTime Then
Dim [date] As DateTime = DirectCast(amount.Value, DateTime)
Console.WriteLine("Date: {0:yyyy-MM-dd}", [date])
End If
Case StreamCellType.Boolean
Console.WriteLine("Flag: {0}", Convert.ToBoolean(amount.Value))
Case StreamCellType.Error
Console.WriteLine("Row {0} contains an error value.", row.RowNumber)
Case Else
' Falls through to the formatted display text for String and anything else.
Console.WriteLine("Text: {0}", amount.Text)
End Select
NextZwei Gewohnheiten sind hier wichtig. Die erste ist die Nullprüfung jedes Indexerzugriffs, da Zeilen spärlich sind und Value ist null für eine leere Zelle, sodass beide Fälle bei derselben Prüfung konvergieren. Die zweite ist das Umwandeln statt Casten: Value enthält den rohen typisierten Wert, und Code, der direkt daraus castet, lehrt einen Fehler, der nur an der einen Datei auftritt, bei der eine Spalte anders gespeichert ist. Es ist völlig vernünftig, Text zu lesen, wenn das Ziel eine String-Spalte ist.
Was meldet StreamCellType?
StreamCellType Werte, gemeldet von StreamCell.Type
| Wert | Gemeldet wann |
|---|---|
Blank | Die Zelle hält keinen Wert. Value ist null |
Number | Die Zelle enthält einen numerischen Wert |
String | Die Zelle enthält Text |
Boolean | Die Zelle enthält TRUE oder FALSE |
Date | Die Zelle enthält ein Datum, das das Datensystem der Arbeitsmappe berücksichtigt |
Error | Die Zelle enthält einen Excel-Fehlerwert |
Es gibt absichtlich kein Formula-Mitglied. Eine Formelezelle meldet den realen Typ ihres gecachten Ergebnisses hier, z. B. Number, und die Formelhaftigkeit wird separat über IsFormula exponiert. Jeder, der das Enum nach einem Fall für Formeln durchsucht, wird keinen finden, und das ist beabsichtigt und kein Versehen.
Was sind die Einschränkungen des Streaming-Readers?
Das Vorwissen darüber verhindert die häufigsten Fehldiagnosen.
Nur die Pfadüberladungen sind wirklich speicherschonend. Dies ist der wichtigste Hinweis auf der Seite. Ein Entwickler, der einen 400-MB-Upload als byte[] übergibt, den Speicheranstieg beobachtet und schließt, dass die Funktion nicht funktioniert, hat genau das erreicht.
Die restlichen Grenzen sind durch das Design festgelegt:
- Schreibgeschützt: Der Streaming-Reader kann nicht ändern oder speichern. Bearbeiten bedeutet
WorkBook.Load. - Nur XLSX: Keine
.xls, keine verschlüsselten Arbeitsmappen und kein Schreiben irgendeiner Art. - Nur vorwärts und einmalig: Es gibt keinen zufälligen Zugriff und kein Zurückspulen. Code, der in einem Blatt herumspringen muss, benötigt
Load. - Keine Stilisierung oder Formatierungsobjekte: Das Aussehen der Zelle wird nicht gezeigt.
- Nur gecachte Formelergebnisse: Der Formelausdruck wird nicht gezeigt und nichts wird neu berechnet.
StreamRows als auch GetSheetNames erfordern eine gültige IronXL-Lizenz, die beim Aufruf der Methode durchgesetzt wird, genau wie bei WorkBook.Load.Ein weiterer Vorbehalt liegt zwischen Einschränkung und Verhalten: speicherschonendes Lesen von einem Pfad ist best-effort. Eine Arbeitsmappe, deren ZIP-Zentralverzeichnis nicht gelesen werden kann, kann darauf zurückfallen, das Paket in den Speicher zu laden.
Wie baue ich eine Streaming-Import-Pipeline?
Das Muster, das produktive Arbeit trägt, ist ein Streaming-Read, das Batch-Schreibvorgänge unterstützt, sodass weder die Quelle noch das Ziel im vollen Umfang im Speicher gehalten wird.
using IronXL;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading.Tasks;
public class TransactionImporter
{
private const int BatchSize = 5000;
public async Task<int> ImportAsync(string path, ITransactionSink sink)
{
StreamReadOptions options = new StreamReadOptions
{
SheetName = "Transactions",
HasHeaderRow = true,
HeaderRowIndex = 0
};
List<TransactionRecord> batch = new List<TransactionRecord>(BatchSize);
int imported = 0;
// Enumeration is lazy: only one row is materialised at a time, so peak memory
// stays flat regardless of how many rows the sheet holds.
foreach (StreamRow row in WorkBook.StreamRows(path, options))
{
TransactionRecord record = MapRow(row);
if (record is null)
{
continue;
}
batch.Add(record);
if (batch.Count == BatchSize)
{
await sink.WriteAsync(batch);
imported += batch.Count;
batch.Clear();
}
}
if (batch.Count > 0)
{
await sink.WriteAsync(batch);
imported += batch.Count;
}
return imported;
}
private static TransactionRecord MapRow(StreamRow row)
{
StreamCell reference = row["Reference"];
StreamCell amount = row["Amount"];
StreamCell posted = row["PostedOn"];
// Required columns missing on this row: skip rather than throw, so one bad
// row does not abort an import of several hundred thousand.
if (reference is null || amount is null)
{
return null;
}
if (amount.Type != StreamCellType.Number)
{
return null;
}
DateTime? postedOn = posted?.Value as DateTime?;
// Optional column that only some source files carry.
string costCentre = row.TryGetCell("CostCentre", out StreamCell centre)
? centre?.Text
: null;
return new TransactionRecord
{
SourceRow = row.RowNumber,
Reference = reference.Text,
Amount = Convert.ToDecimal(amount.Value, CultureInfo.InvariantCulture),
PostedOn = postedOn,
CostCentre = costCentre
};
}
}
public class TransactionRecord
{
public int SourceRow { get; set; }
public string Reference { get; set; }
public decimal Amount { get; set; }
public DateTime? PostedOn { get; set; }
public string CostCentre { get; set; }
}
public interface ITransactionSink
{
Task WriteAsync(IReadOnlyList<TransactionRecord> batch);
}using IronXL;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading.Tasks;
public class TransactionImporter
{
private const int BatchSize = 5000;
public async Task<int> ImportAsync(string path, ITransactionSink sink)
{
StreamReadOptions options = new StreamReadOptions
{
SheetName = "Transactions",
HasHeaderRow = true,
HeaderRowIndex = 0
};
List<TransactionRecord> batch = new List<TransactionRecord>(BatchSize);
int imported = 0;
// Enumeration is lazy: only one row is materialised at a time, so peak memory
// stays flat regardless of how many rows the sheet holds.
foreach (StreamRow row in WorkBook.StreamRows(path, options))
{
TransactionRecord record = MapRow(row);
if (record is null)
{
continue;
}
batch.Add(record);
if (batch.Count == BatchSize)
{
await sink.WriteAsync(batch);
imported += batch.Count;
batch.Clear();
}
}
if (batch.Count > 0)
{
await sink.WriteAsync(batch);
imported += batch.Count;
}
return imported;
}
private static TransactionRecord MapRow(StreamRow row)
{
StreamCell reference = row["Reference"];
StreamCell amount = row["Amount"];
StreamCell posted = row["PostedOn"];
// Required columns missing on this row: skip rather than throw, so one bad
// row does not abort an import of several hundred thousand.
if (reference is null || amount is null)
{
return null;
}
if (amount.Type != StreamCellType.Number)
{
return null;
}
DateTime? postedOn = posted?.Value as DateTime?;
// Optional column that only some source files carry.
string costCentre = row.TryGetCell("CostCentre", out StreamCell centre)
? centre?.Text
: null;
return new TransactionRecord
{
SourceRow = row.RowNumber,
Reference = reference.Text,
Amount = Convert.ToDecimal(amount.Value, CultureInfo.InvariantCulture),
PostedOn = postedOn,
CostCentre = costCentre
};
}
}
public class TransactionRecord
{
public int SourceRow { get; set; }
public string Reference { get; set; }
public decimal Amount { get; set; }
public DateTime? PostedOn { get; set; }
public string CostCentre { get; set; }
}
public interface ITransactionSink
{
Task WriteAsync(IReadOnlyList<TransactionRecord> batch);
}Imports IronXL
Imports System
Imports System.Collections.Generic
Imports System.Globalization
Imports System.Threading.Tasks
Public Class TransactionImporter
Private Const BatchSize As Integer = 5000
Public Async Function ImportAsync(path As String, sink As ITransactionSink) As Task(Of Integer)
Dim options As New StreamReadOptions With {
.SheetName = "Transactions",
.HasHeaderRow = True,
.HeaderRowIndex = 0
}
Dim batch As New List(Of TransactionRecord)(BatchSize)
Dim imported As Integer = 0
' Enumeration is lazy: only one row is materialised at a time, so peak memory
' stays flat regardless of how many rows the sheet holds.
For Each row As StreamRow In WorkBook.StreamRows(path, options)
Dim record As TransactionRecord = MapRow(row)
If record Is Nothing Then
Continue For
End If
batch.Add(record)
If batch.Count = BatchSize Then
Await sink.WriteAsync(batch)
imported += batch.Count
batch.Clear()
End If
Next
If batch.Count > 0 Then
Await sink.WriteAsync(batch)
imported += batch.Count
End If
Return imported
End Function
Private Shared Function MapRow(row As StreamRow) As TransactionRecord
Dim reference As StreamCell = row("Reference")
Dim amount As StreamCell = row("Amount")
Dim posted As StreamCell = row("PostedOn")
' Required columns missing on this row: skip rather than throw, so one bad
' row does not abort an import of several hundred thousand.
If reference Is Nothing OrElse amount Is Nothing Then
Return Nothing
End If
If amount.Type <> StreamCellType.Number Then
Return Nothing
End If
Dim postedOn As DateTime? = CType(posted?.Value, DateTime?)
' Optional column that only some source files carry.
Dim costCentre As String = If(row.TryGetCell("CostCentre", Nothing),
If(Nothing Is Nothing, Nothing, Nothing.Text),
Nothing)
Return New TransactionRecord With {
.SourceRow = row.RowNumber,
.Reference = reference.Text,
.Amount = Convert.ToDecimal(amount.Value, CultureInfo.InvariantCulture),
.PostedOn = postedOn,
.CostCentre = costCentre
}
End Function
End Class
Public Class TransactionRecord
Public Property SourceRow As Integer
Public Property Reference As String
Public Property Amount As Decimal
Public Property PostedOn As DateTime?
Public Property CostCentre As String
End Class
Public Interface ITransactionSink
Function WriteAsync(batch As IReadOnlyList(Of TransactionRecord)) As Task
End InterfaceImports IronXL
Imports System
Imports System.Collections.Generic
Imports System.Globalization
Imports System.Threading.Tasks
Public Class TransactionImporter
Private Const BatchSize As Integer = 5000
Public Async Function ImportAsync(path As String, sink As ITransactionSink) As Task(Of Integer)
Dim options As New StreamReadOptions With {
.SheetName = "Transactions",
.HasHeaderRow = True,
.HeaderRowIndex = 0
}
Dim batch As New List(Of TransactionRecord)(BatchSize)
Dim imported As Integer = 0
' Enumeration is lazy: only one row is materialised at a time, so peak memory
' stays flat regardless of how many rows the sheet holds.
For Each row As StreamRow In WorkBook.StreamRows(path, options)
Dim record As TransactionRecord = MapRow(row)
If record Is Nothing Then
Continue For
End If
batch.Add(record)
If batch.Count = BatchSize Then
Await sink.WriteAsync(batch)
imported += batch.Count
batch.Clear()
End If
Next
If batch.Count > 0 Then
Await sink.WriteAsync(batch)
imported += batch.Count
End If
Return imported
End Function
Private Shared Function MapRow(row As StreamRow) As TransactionRecord
Dim reference As StreamCell = row("Reference")
Dim amount As StreamCell = row("Amount")
Dim posted As StreamCell = row("PostedOn")
' Required columns missing on this row: skip rather than throw, so one bad
' row does not abort an import of several hundred thousand.
If reference Is Nothing OrElse amount Is Nothing Then
Return Nothing
End If
If amount.Type <> StreamCellType.Number Then
Return Nothing
End If
Dim postedOn As DateTime? = CType(posted?.Value, DateTime?)
' Optional column that only some source files carry.
Dim costCentre As String = If(row.TryGetCell("CostCentre", Nothing),
If(Nothing Is Nothing, Nothing, Nothing.Text),
Nothing)
Return New TransactionRecord With {
.SourceRow = row.RowNumber,
.Reference = reference.Text,
.Amount = Convert.ToDecimal(amount.Value, CultureInfo.InvariantCulture),
.PostedOn = postedOn,
.CostCentre = costCentre
}
End Function
End Class
Public Class TransactionRecord
Public Property SourceRow As Integer
Public Property Reference As String
Public Property Amount As Decimal
Public Property PostedOn As DateTime?
Public Property CostCentre As String
End Class
Public Interface ITransactionSink
Function WriteAsync(batch As IReadOnlyList(Of TransactionRecord)) As Task
End InterfaceDie Batchverarbeitung ist das, was das hält. Zeilen kommen eine nach der anderen an, sammeln sich in einem Festgrößenpuffer und werden in die Datenbank oder Warteschlange gespült, wenn der Puffer voll ist. Spitzenspeicher wird durch die Batchgröße begrenzt und nicht durch die Zeilenanzahl, was bedeutet, dass derselbe Code eine Datei mit 5.000 und 5.000.000 Zeilen identisch handhabt.
Das Überspringen fehlerhafter Zeilen anstelle des Werfens ist eine bewusste Entscheidung für Massenimporte. Eine nicht analysierbare Zeile in mehreren Hunderttausenden sollte den Vorgang nicht abbrechen, und die Aufzeichnung von RowNumber neben jedem Datensatz gibt Betreibern die Möglichkeit, einen schlechten Wert zu seiner Zelle in der Quelldatei zurückzuverfolgen.
Welche Randfälle sollte ich bearbeiten?
GetSheetNames gibt jedes Blatt in der Arbeitsmappe zurück, einschließlich Diagrammblättern. Ein Diagrammblatt enthält keine Zeilen, sodass das Übergeben seines Indexes an StreamRows eine leere Sequenz ergibt, anstatt einen Fehler zu verursachen. Code, der jeden Blattindex durchläuft, wird darauf stoßen, und ein leeres Ergebnis dort ist erwartet.
using IronXL;
using System;
using System.Collections.Generic;
// GetSheetNames returns every sheet in workbook order, including chartsheets.
// List position equals the index that StreamRows accepts.
IReadOnlyList<string> sheetNames = WorkBook.GetSheetNames("large-export.xlsx");
for (int i = 0; i < sheetNames.Count; i++)
{
int rowCount = 0;
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx", i))
{
rowCount++;
}
// A chartsheet holds no rows, so it streams as an empty sequence rather than
// raising an error. Zero rows here is expected, not a failure to investigate.
if (rowCount == 0)
{
Console.WriteLine("[{0}] {1}: no rows (chartsheet or empty worksheet)", i, sheetNames[i]);
}
else
{
Console.WriteLine("[{0}] {1}: {2} rows", i, sheetNames[i], rowCount);
}
}using IronXL;
using System;
using System.Collections.Generic;
// GetSheetNames returns every sheet in workbook order, including chartsheets.
// List position equals the index that StreamRows accepts.
IReadOnlyList<string> sheetNames = WorkBook.GetSheetNames("large-export.xlsx");
for (int i = 0; i < sheetNames.Count; i++)
{
int rowCount = 0;
foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx", i))
{
rowCount++;
}
// A chartsheet holds no rows, so it streams as an empty sequence rather than
// raising an error. Zero rows here is expected, not a failure to investigate.
if (rowCount == 0)
{
Console.WriteLine("[{0}] {1}: no rows (chartsheet or empty worksheet)", i, sheetNames[i]);
}
else
{
Console.WriteLine("[{0}] {1}: {2} rows", i, sheetNames[i], rowCount);
}
}Imports IronXL
Imports System
Imports System.Collections.Generic
' GetSheetNames returns every sheet in workbook order, including chartsheets.
' List position equals the index that StreamRows accepts.
Dim sheetNames As IReadOnlyList(Of String) = WorkBook.GetSheetNames("large-export.xlsx")
For i As Integer = 0 To sheetNames.Count - 1
Dim rowCount As Integer = 0
For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx", i)
rowCount += 1
Next
' A chartsheet holds no rows, so it streams as an empty sequence rather than
' raising an error. Zero rows here is expected, not a failure to investigate.
If rowCount = 0 Then
Console.WriteLine("[{0}] {1}: no rows (chartsheet or empty worksheet)", i, sheetNames(i))
Else
Console.WriteLine("[{0}] {1}: {2} rows", i, sheetNames(i), rowCount)
End If
NextImports IronXL
Imports System
Imports System.Collections.Generic
' GetSheetNames returns every sheet in workbook order, including chartsheets.
' List position equals the index that StreamRows accepts.
Dim sheetNames As IReadOnlyList(Of String) = WorkBook.GetSheetNames("large-export.xlsx")
For i As Integer = 0 To sheetNames.Count - 1
Dim rowCount As Integer = 0
For Each row As StreamRow In WorkBook.StreamRows("large-export.xlsx", i)
rowCount += 1
Next
' A chartsheet holds no rows, so it streams as an empty sequence rather than
' raising an error. Zero rows here is expected, not a failure to investigate.
If rowCount = 0 Then
Console.WriteLine("[{0}] {1}: no rows (chartsheet or empty worksheet)", i, sheetNames(i))
Else
Console.WriteLine("[{0}] {1}: {2} rows", i, sheetNames(i), rowCount)
End If
NextDatumszellen beachten das Datensystem der Arbeitsmappe, einschließlich der 1904-basierten Arbeitsmappen, die Excel für Mac erstellt. Keine Anpassung ist im aufrufenden Code nötig.
Wohin gehe ich als Nächstes?
StreamRows deckt eine Aufgabe gut ab: Werte schnell aus einer großen XLSX-Datei zu erhalten, mit einem Speicher, der flach bleibt. Alles über das Lesen von Werten hinaus gehört zum vollständigen Arbeitsmappenmodell und die Vermischung der beiden in einer Pipeline ist normal. Streamen, um zu validieren oder zu importieren, dann Load die kleinere Arbeitsdatei, wenn Bearbeitungen erforderlich sind.
Für die umgebenden Funktionen behandelt das C# Lesen von XLSX-Dateien How-To das Standardlesen, das Importieren von Excel-Dateien How-To behandelt Datenimportmuster, und das Lesen von Excel-Dateien in C#-Tutorial arbeitet die Grundlagen durch. Die Fehlerbehebungsseite zu Dateigrößenbeschränkungen behandelt formatbezogene Zeilen- und Spaltenobergrenzen, und die WorkBook-API-Referenz dokumentiert die vollständige Klasse.
Ahmad ist ein Full-Stack-Entwickler mit einer soliden Grundlage in C#, Python und Webtechnologien. Er hat ein großes Interesse am Aufbau skalierbarer Softwarelösungen und genießt es, zu erkunden, wie Design und Funktionalität in realen Anwendungen aufeinandertreffen.