Jak odczytywać bardzo duże pliki Excel w C# z użyciem strumieniowania jednokierunkowego
Arkusz kalkulacyjny zawierający kilkaset tysięcy wierszy łamie zwykłe podejście. WorkBook.Load tworzy kompletny model w pamięci roboczej skoroszytu, co umożliwia edycję, stylizację, formuły oraz losowy dostęp, i to właśnie dlatego eksport 400 MB może zająć minuty i zużyć kilka gigabajtów, zanim zostanie odczytana pierwsza wartość.
Strumieniowy odczytnik jednokierunkowy IronXL, WorkBook.StreamRows, istnieje do zadań wymagających jedynie wartości. Za każdym razem zwraca jeden wiersz bezpośrednio z dysku zamiast realizować skoroszyt, co powoduje, że pamięć jest stała niezależnie od liczby wierszy w arkuszu.
Większe znaczenie ma to, gdzie przebiega linia, niż samo API, ponieważ błędne odczytanie tej linii jest głównym powodem niewłaściwego użytkowania funkcji. StreamRows jest tylko do odczytu, tylko XLSX i tylko jednokierunkowy: szybka droga do masowego wydobycia wartości. Edycja, stylizacja, formuły, wykresy, losowy dostęp i formaty inne niż XLSX pozostają zadaniem WorkBook.Load.
StreamRows i nie będą się kompilować.Wskaż StreamRows na ścieżkę do pliku i wyegzekwuj wynik. Za kulisami przeładowanie ścieżki jako string czyta części skoroszytu z dysku, a tylko jeden wiersz jest realizowany na raz, co pozwala na zachowanie stałej pamięci w całkowicie dużym arkuszu.
-
1Zainstaluj IronXL z NuGet Package Manager
-
2Skopiuj i uruchom ten fragment kodu.
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 -
3Wdrożenie do testowania w środowisku produkcyjnym
Rozpocznij korzystanie z IronXL w swoim projekcie już dziś z darmową wersją próbną
Minimalny proces (5 kroków)
- Zainstalować lub zaktualizować do IronXL 2026.9.2 lub nowszej oraz zastosować ważny klucz licencyjny
- Wywołaj
WorkBook.GetSheetNames(path), jeśli trzeba odkryć celowy arkusz - Wywołaj
WorkBook.StreamRows(path, ...)z indeks arkusza, nazwą arkusza lubStreamReadOptions - Wyodrębnij zwrócone
IEnumerable<StreamRow>, sprawdzając null przy każdym dostępie do komórki - Sprawdź
StreamCell.Typeprzed odczytaniemValuei zapisz wyniki w pakietach
Jak wybrać między StreamRows a WorkBook.Load?
Podział to kwestia potrzeb pracy, a nie samego rozmiaru pliku. Plik 50 MB, który potrzebuje przestylowania komórki, kwalifikuje się do Load. Plik 500 MB, który potrzebuje, aby trzy kolumny były wprowadzone do bazy danych, kwalifikuje się do StreamRows.
Wybór między odczytowaniem strumieniowym a pełnym modelem skoroszytu
| Wymagania | StreamRows | WorkBook.Load |
|---|---|---|
| Masowe wyodrębnianie wartości, importy, ETL, walidacja | Tak | Tak (wolniej) |
| Edycja lub zapisywanie | Nie | Tak |
| Stylizacja, formatowanie obiektów | Nie | Tak |
| Wyrażenia formuł i przeliczanie | Nie (tylko rezultaty buforowane) | Tak |
| Losowy dostęp do dowolnych komórek | Nie (tylko jednokierunkowy) | Tak |
| XLS, CSV, TSV, zaszyfrowane skoroszyty | Nie | Tak |
| Wykresy i obrazy | Nie | Tak |
Różnica jest wystarczająco duża, by zmienić sposób projektowania pracy. Strumieniowanie wszystkich 500 000 wierszy z 23,4 MB skoroszytu zajęło około sześciu sekund i zająło około 75 MB, przy czym pierwszy wiersz był dostępny w ciągu ćwierć sekundy; WorkBook.Load dla tego samego pliku jest dramatycznie cięższy pod oboma względami. Sprzęt i kształt skoroszytu wpływają na te liczby, a skoroszyty z niezwykle szerokimi wierszami lub ciężkimi tabelami ciągów wspólnych lądują różnie. Przewodnik po wydajności ładowania danych obejmuje ekwiwalentne kompromisy po stronie pisania.
Jak strumieniować wiersze ze skoroszytu?
WorkBook.StreamRows to metoda statyczna w WorkBook. Podaj źródło i arkusz, a wyegzekwuj to, co wraca.
Wejscie
Pół miliona wierszy danych transakcyjnych, osiem kolumn szerokości, 23,4 MB na dysku. Excel otwiera to bez problemów; problem zaczyna się, gdy kod próbuje wciągnąć całość do pamięci.
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
NextWynik
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
Jedna linia na komórkę, ponieważ pętla chodzi row.Cells zamiast po ustalonym zestawie kolumn. RowNumber jest zerowy, więc przykład dodaje jeden, aby dopasować wynik do numeracji Excela. Zauważ, że nagłówek przychodzi tutaj jako zwykły wiersz: bez dostarczenia StreamReadOptions, TxnId i Date pojawiają się jako wartości komórek w wierszu 1 zamiast nazywać kolumny.
Zwracany typ to IEnumerable<StreamRow>, a różnica, która ma znaczenie, to fakt, że nic nie jest czytane, dopóki sekwencja nie zostanie iterowana. Wiersze są produkowane jeden po drugim, gdy pętla się toczy, więc foreach nad arkuszem 500 000 wierszy trzyma jedynie jeden wiersz w pamięci, a nie pół miliona. Konsekwencją jest to, że sekwencja jest jednokierunkowa i jednokrotna: nie można wracać do wcześniejszego wiersza i nie można indeksować się w środek jednego. Operatory LINQ komponują się z nim normalnie, co oznacza, że .Take(1000) czyta tysiąc wierszy i tam się zatrzymuje.
Każdy StreamRow niesie tylko komórki z zawartością, co jest omówione poniżej, w sekcji praca z StreamRow.
Które przepakowanie powinienem użyć?
Dziewięć przepakowań obejmuje trzy źródła i trzy sposoby nazywania arkusza. Źródło jest decyzją, która ma znaczenie, ponieważ tylko przepakowania string path czytają leniwie z dysku. Przepakowania Stream i byte[] muszą przechowywać zawartość rozpakowaną paczki w pamięci na czas odczytu.
Dziewięć przepakowań StreamRows, wszystkie zwracające IEnumerable<StreamRow>
| Przepakowanie | Nisko-pamięciowe |
|---|---|
StreamRows(string path, int sheetIndex = 0) | Tak |
StreamRows(string path, string sheetName) | Tak |
StreamRows(string path, StreamReadOptions options) | Tak |
StreamRows(Stream stream, int sheetIndex = 0) | Nie |
StreamRows(Stream stream, string sheetName) | Nie |
StreamRows(Stream stream, StreamReadOptions options) | Nie |
StreamRows(byte[] data, int sheetIndex = 0) | Nie |
StreamRows(byte[] data, string sheetName) | Nie |
StreamRows(byte[] data, StreamReadOptions options) | Nie |
Przepakowania Stream i byte[] istnieją dla wygody, gdy plik już znajduje się w pamięci, takie jak przesłanie, które zostało buforowane. Strumieniują one wiersz po wierszu, więc unikają zbudowania pełnego modelu skoroszytu, ale rozpakowana zawartość pozostaje dostępna przez cały czas odczytu. Spodziewaj się, że osiągnie około dziesięciu razy większy rozmiar pliku na dysku, więc skoroszyt 23,4 MB zajmuje nieco ponad 200 MB, a nie wartość sugerowaną przez jego rozmiar pliku. Użyj ścieżki pliku dla największych plików.
Wszystkie trzy zwracają identyczne wiersze i sumy; kosztem jest pamięć, a nie szybkość ani poprawność
| Źródło | Czas upłynięty | Szczytowa pamięć |
|---|---|---|
string path | 6,3 s | 75 MB |
Stream | 6,2 s | 309 MB |
byte[] | 6,3 s | 291 MB |
Czas upływu wynosi zasadniczo identyczny wśród trzech, co warto zauważyć: wybranie złego przepakowania nie powoduje spowolnienia odczytu, powoduje jedynie jego obciążenie. Praca, która wygodnie pasuje do pamięci, nie odczuje różnicy aż do momentu, gdy plik urośnie lub limit kontenera zostanie obniżony.
Jak wybrać arkusz?
Wybór arkusza ma trzy formy: indeks zerowy, dokładna nazwa arkusza pasująca z uwzględnieniem małych/dużych liter lub instancja StreamReadOptions. Nieznana nazwa arkusza lub indeks poza zakresem powoduje 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 TryPrzekazanie żadnego argumentu arkusza strumieniuje pierwszy arkusz, ponieważ sheetIndex domyślnie jest 0. StreamReadOptions jest jedyną drogą, która obsługuje wiersze nagłówkowe, więc sięgnij po to natychmiast, gdy kolumny potrzebują nazw.
Jak odkryć arkusze przed strumieniowaniem?
WorkBook.GetSheetNames wyświetla każdy arkusz w kolejności skoroszytu bez ładowania zawartości skoroszytu. Czyta tylko listę części skoroszytu, więc pozostaje tani nawet przy bardzo dużym pliku: około ćwierć sekundy na 23,4 MB, 500 000-wierszowym skoroszycie, co trwa tyle samo na pliku o kilku kilobajtach. To sprawia, że jest to naturalne pierwsze wywołanie dla pliku pochodzącego z zewnętrznego systemu, którego układ nie jest znany z góry.
Trzy przepakowania GetSheetNames, każde zwracające IReadOnlyList<string>
| Przepakowanie | Źródło |
|---|---|
GetSheetNames(string path) | Plik na dysku |
GetSheetNames(Stream stream) | Otwarty strumień |
GetSheetNames(byte[] data) | Bufor w pamięci |
Pozycja na zwróconej liście odpowiada indeksowi arkusza, co przyjmuje StreamRows, więc dwa API pasują bezpośrednio: indeks 2 na tej liście to arkusz, który czyta StreamRows(path, 2).
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
NextJak czytać wiersze według nazwy kolumny?
Ustawienie HasHeaderRow nazywa kolumny i pozwala na odczyt wierszy według nazwy nagłówka. Wiersz nagłówka jest zużywany na nazwanie i nie jest zwracany jako dane, a wszelkie wiersze przed HeaderRowIndex są pomijane, co obsługuje powszechny przypadek tytułu lub wstępu zamieszczonego nad prawdziwym nagłówkiem.
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. Bez tego zarówno indeksator łańcucha, jak i TryGetCell rzucają InvalidOperationException.Obsługa nagłówków jest celowo rygorystyczna. Jeśli arkusz nie ma wiersza na lub przed skonfigurowanym HeaderRowIndex, enumeracja wywołuje InvalidOperationException z komunikatem "brak wiersza nagłówkowego", i wywołuje, jak tylko wiersz danych przekroczy indeks nagłówka. To zapewnia, że konsument używający Take lub wczesnego break od razu widzi błędną konfigurację zamiast potajemnie niczego nie czytając.
Dopasowanie nazw kolumn jest bezduszności i przycina otaczające białe znaki. Rozwiązywanie duplikatów nazw nagłówków do pierwszej, najbliższej lewej pasującej kolumny.
Co konfiguruje StreamReadOptions?
Właściwości StreamReadOptions, ustawione przez inicjalizator obiektu
| Właściwość | Typ | Default | Zachowanie |
|---|---|---|---|
SheetIndex | int | 0 | Indeks arkusza oparty na zerze. Ignorowane, gdy @SheetName jest ustawione |
SheetName | string | null | Nazwa arkusza, pasująca z uwzględnieniem wielkości liter. Ma pierwszeństwo nad SheetIndex |
HasHeaderRow | bool | false | Gdy prawda, wiersz przy HeaderRowIndex nazywa kolumny i nie jest uwzględniany jako dane |
HeaderRowIndex | int | 0 | Zerowy wiersz arkusza trzymający nagłówek. Wiersze przed nim są pomijane |
Jak obsługiwać opcjonalne kolumny?
Dwa nazywane akcesory różnią się tym, jak traktują kolumnę, której nie ma w nagłówku, i wybór niewłaściwego jest tym, co przekształca akceptowalny plik źródłowy w upadek. Indeksator ciągowy wywołuje ArgumentException; TryGetCell zwraca false.
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 odpowiada węższemu pytaniu, niż się wydaje: informuje, czy nagłówek zawiera nazwę kolumny, a nie czy ten konkretny wiersz ma tam wartość. Wiersz z rzadkim luką w znanej kolumnie zwraca true z null, więc nadal potrzebna jest sprawdzenie wartości null na wyjściu. Użyj TryGetCell dla dowolnej kolumny, która może być nieobecna w niektórych plikach źródłowych, a indeksator ciągowy tylko tam, gdzie kolumna jest gwarantowana.
Czy i jak pracować z StreamRow?
StreamRow to jeden wiersz wyprodukowany podczas wyliczania. Ujawnia swoje pozycje, komórki, które faktycznie zawiera, oraz zarówno pozycyjne, jak i nazwane wyszukiwania.
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
NextCzłonkowie StreamRow, z dostępem zarówno typu pozycyjnego, jak i nazwanego
| Członek | Typ | Zachowanie |
|---|---|---|
RowNumber | int | Oparty na zerze. Wiersz Excela 1 to RowNumber 0 |
Cells | IReadOnlyList<StreamCell> | Rzadki. Tylko kolumny z zawartością są obecne |
Header | IReadOnlyList<string> | Nazwy kolumn ułożone według kolumny, więc Header[i] nazwy kolumny i. Pusta kolumna nagłówkowa to null, a samo Header to null, gdy nie skonfigurowano nagłówka |
this[int columnIndex] | StreamCell | Komórka na indeksie kolumny opartej na zerze lub null dla rzadkiej luki |
this[string columnName] | StreamCell | Komórka pod nazwanym kolumną nagłówka. Wywołuje ArgumentException, gdy nie ma nazwy |
TryGetCell(string, out StreamCell) | bool | true, gdy nagłówek zawiera nazwę, false, gdy tego nie robi |
Header wynosi null, chyba ze StreamReadOptions.HasHeaderRow zostal ustawiony. Chronić to przed iteracją, inaczej pętla odwołuje się do pustej listy.Rzadkość to cecha, która kształtuje kod wywołujący. Wiersz nie jest stało-szerokim zapisem: arkusz z kolumnami od A do F produkuje wiersze, które zawierają trzy komórki tam, gdzie wypełniono trzy kolumny, a indeksator pozycyjny zwraca null dla luk. RowNumber, który jest oparcus najpierwszy, jest zgodny z resztą IronXL, gdzie indeksatory numeryczne są zero-based, podczas gdy adresy ciągów stylu A1 nie są.
Jak czytać well-typed wartości ze StreamCell?
StreamCell to niezmienny zrzut jednej komórki. W przeciwieństwie do normalnego Cell, nie jest wspierany przez skoroszyt i nie można go używać do zapisywania wartości z powrotem.
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)
NextCzłonkowie StreamCell, obejmują położenie, typ i wartość
| Członek | Typ | Zachowanie |
|---|---|---|
ColumnIndex | int | Indeks kolumny opartej na zerze |
ColumnLetter | string | Litera kolumny arkusza, na przykład "A", "C" lub "AA" |
Type | StreamCellType | Rodzaj wartości przechowywanej. Dla komórki formuły, typ zbuforowanego wyniku |
Value | object | Surowa typowana wartość. null dla pustej komórki |
Text | string | Sformatowany tekst wyświetlany, jak pokazuje go Excel |
IsFormula | bool | true, gdy komórka zawiera formułę |
Value jest skrzynkowane, więc to, do czego go konwertujesz, wynika z Type:
NumberdajedoubleStringdajestringBooleandajeboolDatedajeDateTimeBlankdajenull
Sprawdzanie Type przed dotknięciem Value to różnica między importem, który przetrwa prawdziwe dane, a tym, który wywołuje na wierszu 40 000.
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
NextDwa nawyki mają tu znaczenie. Pierwszym jest sprawdzenie null przy każdym dostępie do indeksatora, ponieważ wiersze są rzadkie, a Value to null dla pustej komórki, więc oba przypadki zbliżają się do tego samego sprawdzenia. Drugie to konwersja zamiast rzutowania: Value przechowuje surową typowaną wartość, a kod, który rzutuje bezpośrednio z niej, uczy się buga, który pojawia się tylko na jednym pliku, w którym kolumna jest przypadkowo przechowywana inaczej. Czytanie Text zamiast jest całkowicie rozsądne, gdy celem jest kolumna ciągu.
Czemu StreamCellType raportuje?
StreamCellType wartości, zgłaszane przez StreamCell.Type
| Wartość | Zgłaszane, gdy |
|---|---|
Blank | Komórka nie przechowuje żadnej wartości. Value jest null |
Number | Komórka przechowuje wartość liczbową |
String | Komórka przechowuje tekst |
Boolean | Komórka przechowuje TRUE lub FALSE |
Date | Komórka przechowuje datę, zgodnie z systemem daty skoroszytu |
Error | Komórka przechowuje wartość błędu Excel |
Celowo nie ma członka Formula. Komórka formuły raportuje rzeczywisty typ swojego zbuforowanego wyniku tutaj, na przykład Number, a formula-ness jest ujawniana osobno przez IsFormula. Każdy, kto szuka enum dla przypadku formuły, go nie znajdzie, i to jest z zamysłem, a nie z przeoczeniem.
Jakie są ograniczenia strumieniowego czytelnika?
Znajomość tych informacji z góry zapobiega najczęstszym błędnym diagnozom.
Tylko przecielecia ścieżkowe są naprawdę nisko-pamięciowe. To najważniejsze zastrzeżenie na stronie. Programista, który przesyła 400 MB jako byte[], obserwuje, jak pamięć rośnie, i dochodzi do wniosku, że funkcja jest uszkodzona, trafił dokładnie to.
Pozostałe granice są ustalone przez projekt:
- Tylko do odczytu: Strumieniowy czytnik nie może modyfikować ani zapisywać. Edycja oznacza
WorkBook.Load. - Wyłącznie XLSX: Brak
.xls, brak zaszyfrowanych skoroszytów i brak zapisu jakiegokolwiek rodzaju. - Jednokierunkowe i jednokrotne: Nie ma losowego dostępu i żadnego przewijania. Kod, który musi skakać po arkuszu, potrzebuje
Load. - Brak stylizacji lub formatowania obiektów: Wygląd komórek nie jest odsłonięty.
- Wyniki formuły tylko do buforowania: Wyrażenie formuły nie jest ujawniane i nic nie jest przeliczane.
StreamRows, jak i GetSheetNames wymagają ważnego IronXL, wymuszonego podczas wywołania metody, tak samo jak w przypadku WorkBook.Load.Jeszcze jedno zastrzeżenie leży między ograniczeniem a zachowaniem: nisko-pamięciowe odczytywanie z ścieżki jest najlepszym wysiłkiem. Skoroszyt, którego centralny katalog zip nie może być odczytany, może wrócić do ładowania paczki do pamięci.
Jak zbudować strumieniowy pipeline importowy?
Wzorzec, który obsługuje pracę produkcji, to strumieniowy odczyt zasilający zapisy pakiety, więc ani źródło, ani cel nie są trzymane w pamięci w pełnym rozmiarze.
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 InterfacePakietowanie jest tym, co utrzymuje to działanie. Wiersze przybywają jeden po drugim, akumulują się w buforku o stałym rozmiarze i są spłukiwane do bazy danych lub kolejki, gdy buforek się zapełnia. Szczytowa pamięć jest ograniczona przez rozmiar pakietu, a nie przez liczbę wierszy, co oznacza, że ten sam kod obsługuje plik o 5 000 wierszy i plik o 5 000 000 wierszy identycznie.
Pomijanie uszkodzonych wierszy zamiast wywoływania jest świadomym wyborem dla masowych importów. Jeden nieparsowalny wiersz w kilkuset tysiącach nie powinien przerywać przebiegu, a zapis RowNumber obok każdego rekordu daje operatorom możliwość śledzenia złej wartości do jej komórki w pliku źródłowym.
Jakie przypadki brzegowe powinienem obsłużyć?
GetSheetNames zwraca każdy arkusz w skoroszycie, w tym arkusze wykresów. Arkusz wykresu nie zawiera wierszy, więc przekazanie jego indeksu do StreamRows daje pustą sekwencję zamiast wywoływania błędu. Kod, który pętluje przez każdy indeks arkusza, napotka to, i pusty wynik tam jest oczekiwany.
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
NextKomórki dat honorują system daty skoroszytu, w tym te oparte na roku 1904, które produkuje Excel dla Mac. Nie są potrzebne żadne korekty w kodzie wywołującym.
Dokąd się udać dalej?
StreamRows obejmuje jedno zadanie dobrze: szybkie wydobywanie wartości z dużego pliku XLSX, z pamięcią, która pozostaje płaska. Wszystko poza odczytem wartości należy do pełnego modelu skoroszytu, a mieszanie tych dwóch w jednym pipeline jest normalne. Przepływ do walidacji lub importu, a następnie Load mniejszy plik roboczy, gdy potrzebne są edycje.
Dla otaczającej funkcjonalności, C# jak czytać plik XLSX obejmuje standardowe metody odczytu, Jak importować pliki Excel obejmuje wzorce importu danych, a Lekcja czytania plików Excel w C# przechodzi przez podstawy. Strona z rozwiązywaniem problemów na temat ograniczeń rozmiaru pliku obejmuje pułapy poziomu formatu dla wierszy i kolumn, a Dokumentacja API WorkBook dokumentuje całą klasę.
Ahmad to full-stack developer z solidnym fundamentem w C#, Pythonie i technologiach webowych. Ma głębokie zainteresowanie tworzeniem skalowalnych rozwiązań oprogramowania i cieszy się badaniem, jak projektowanie i funkcjonalność spotykają się w rzeczywistych aplikacjach.