C# ile Çok Büyük Excel Dosyalarını Sadece İleriye Doğru Akışla Nasıl Okunur
Birkaç yüz bin satıra sahip bir elektronik tablo, alışılmış yöntemi kırar. WorkBook.Load, kurgusal bir model oluşturur, bu nedenle düzenleme, stil, formüller ve rastgele erişim mümkündür ve bu nedenle 400 MB'lik bir dışa aktarma, ilk değerden önce birkaç gigabayt tüketir ve okuma birkaç dakika sürebilir.
IronXL'nin sadece ileriye doğru akış okuyucusu WorkBook.StreamRows, sadece değerlere ihtiyacı olan işler için vardır. Diskten doğrudan birer satır sunar, böylece elektronik tablo kaç satır içerirse içersin bellek seviyesini sabit tutar.
Çizginin nerede düştüğünü anlamak, API'nin kendisinden daha önemlidir, çünkü bu hatalı okunursa, özellik yanlış kullanılır. StreamRows, salt okuma, yalnızca XLSX ve sadece ileri doğru: toplu değer çıkarımı için hızlı bir yol. Düzenleme, stil, formüller, grafikler, rastgele erişim ve XLSX olmayan formatlar tüm WorkBook.Load işini yapar.
StreamRows sunmazlar ve derlemede başarısız olurlar.Bir dosya yoluna StreamRows işaret edin ve sonucu sıralayın. Sahneler arkasında, dize yolu yüklemesi diskten tembel bir şekilde elektronik tablonun parçalarını okur ve sadece bir satır kurgusallaştırılır, böylece bellek sonsuz büyüklükte bir sayfada sabit kalır.
-
1IronXL ile NuGet Package Manager'u yükleyin
-
2Bu kod parçacığını kopyalayın ve çalıştırın.
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 -
3Canlı ortamınızda test için dağıtım yapın
Projenizde IronXL'yi bugün ücretsiz deneme sürümü ile kullanmaya başlayın
Asgari İş Akışı (5 adım)
- IronXL 2026.9.2 veya daha sonraki sürümleri yükleyin veya yükseltin ve geçerli bir lisans anahtarı uygulayın
- Hedef sayfa keşfedilmeliyse
WorkBook.GetSheetNames(path)çağırın - Sayfa dizini, sayfa adı veya
StreamReadOptionsileWorkBook.StreamRows(path, ...)çağırın - Döndürülen
IEnumerable<StreamRow>sıralayın, her hücre erişimini null kontrol edin Valueokumadan önceStreamCell.Typekontrol edin ve sonuçları gruplar halinde yazın
StreamRows ile WorkBook.Load arasında nasıl seçim yapmalıyım?
Bölme, işin neye ihtiyacı olduğu sorusudur, yalnızca dosya boyutunun değil. Yeniden biçimlendirilmeye ihtiyaç duyan 50 MB'lik bir dosya Load'ya aittir. Üç sütunu bir veritabanına itilmesi gereken 500 MB'lik bir dosya StreamRows'ya aittir.
Akış okuyucusu ile tam iş defteri modeli arasında seçim yapma
| Gereklilik | StreamRows | WorkBook.Load |
|---|---|---|
| Toplu değer çıkarımı, dışa aktarma/aktarma, ETL, doğrulama | Evet | Evet (daha yavaş) |
| Düzenleme veya kaydetme | Hayır | Evet |
| Stil, biçimlendirme nesneleri | Hayır | Evet |
| Formül ifadeleri ve yeniden hesaplama | Hayır (yalnızca önbelleğe alınmış sonuçlar) | Evet |
| Rastgele hücrelere erişim | Hayır (sadece ileriye doğru) | Evet |
| XLS, CSV, TSV, şifreli çalışma kitapları | Hayır | Evet |
| Grafikler ve resimler | Hayır | Evet |
Fark, bir işin nasıl tasarlandığını değiştirecek kadar geniştir. 23,4 MB bir defterin 500.000 satırını akıtmak yaklaşık altı saniye sürdü ve yaklaşık 75 MB tuttu, ilk satır çeyrek saniyede ulaşılabilir; Aynı dosyadaki WorkBook.Load her iki açıdan da dramatik olarak daha ağırdır. Donanım ve iş defteri şekli bu sayıları hareket ettirir ve alışılmadık şekilde geniş satırlar veya ağır paylaşımlı dize tabloları olan iş defterleri yine farklı yerlerde biter. veri yükleme performans rehberi yazma tarafındaki eşdeğer ödünleşmeleri kapsar.
Bir Çalışma Kitabı Satırlarını Nasıl Akıtırım?
WorkBook.StreamRows, WorkBook üzerinde bir statik yöntemdir. Ona bir kaynak ve bir çalışma sayfası verin ve geri dönenleri sıralayın.
Girdi
Diskte 23,4 MB olan yarım milyon satırlık işlem verisi, sekiz sütun genişliğinde. Excel onu problem yaşamadan açıyor; kod onun tamamını belleğe almaya çalıştığında sorun başlar.
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
NextÇıktı
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
Yalnızca her hücre için bir satır, çünkü döngü row.Cells sabit bir sütun seti yerine yürüyor. RowNumber sıfır tabanlıdır, bu yüzden örnek çıktıyı Excel'in kendi numaralandırmasıyla hizalamak için bir ekler. Başlığın burada sıradan bir satır olarak geldiğini unutmayın: StreamReadOptions sağlanmadıysa, TxnId ve Date sütunları adlandırmak yerine 1. satırdaki hücre değerleri olarak gelir.
Dönüş türü IEnumerable<StreamRow> türündedir ve önemli fark, dizilimin bir işleme tabi tutulana kadar hiçbir şeyin okunmamasıdır. Satırlar tek tek üretilir ve bu yüzden 500.000 satırlık bir sayfa üzerindeki bir foreach tek bir satır tutar bellek yerine 500.000'i. Sonuç şu ki, dizilim tek geçişli ve sadece ileriye doğru: önceki bir satıra geri gitmek veya birinin ortasına indeks yerleştirmek mümkün değildir. LINQ operatörleri ona normal şekilde birleşir, bu .Take(1000) bir bin satır okur ve burada durduğu anlamına gelir.
Her StreamRow yalnızca içerik tablosu altında ele alınan hücreleri içerir bir StreamRow ile çalışmak aşağıdadır.
Hangi Aşırı Yüklemeyi Kullanmalıyım?
Dokuz aşırı yükleme üç kaynağı ve çalışma sayfasını adlandırmanın üç yolunu kapsar. Kaynak, önemli karardır, çünkü yalnızca string path aşırı yüklemeleri tembelliğe göre diskten okur. Stream ve byte[] aşırı yüklemeleri, paketin çıkartılmış içeriğini okuma süresi boyunca bellekte tutmalıdır.
Dokuz StreamRows aşırı yükleme, tarafından belirtilenler IEnumerable<StreamRow>
| Aşırı Yükleme | Düşük Bellek |
|---|---|
StreamRows(string path, int sheetIndex = 0) | Evet |
StreamRows(string path, string sheetName) | Evet |
StreamRows(string path, StreamReadOptions options) | Evet |
StreamRows(Stream stream, int sheetIndex = 0) | Hayır |
StreamRows(Stream stream, string sheetName) | Hayır |
StreamRows(Stream stream, StreamReadOptions options) | Hayır |
StreamRows(byte[] data, int sheetIndex = 0) | Hayır |
StreamRows(byte[] data, string sheetName) | Hayır |
StreamRows(byte[] data, StreamReadOptions options) | Hayır |
Stream ve byte[] aşırı yüklemeleri, bir dosya bellekte oturduğunda kullanışlıdır, örneğin tamponlanmış bir yükleme. Yine de satır satır akmaya devam ederler, bu yüzden tam bir iş defteri modeli yapılandırmaktan kaçınırlar, ancak paketin çıkartılmış içeriği tüm okuma süresince depoda kalır. Disk üzerindeki dosyanın yaklaşık on katı kadar çalışmasını bekleyin, böylece bir 23,4 MB iş defteri, kendi dosya boyutunun önerdiği rakam yerine 200 MB'yi biraz geçer. En büyük dosyalar için bir dosya yolu kullanın.
Üçü de aynı satırları ve toplamları döndürür; maliyet hız veya doğruluk değil, bellek
| Kaynak | Geçen Süre | Tepe bellek |
|---|---|---|
string path | 6.3 s | 75 MB |
Stream | 6.2 s | 309 MB |
byte[] | 6.3 s | 291 MB |
Geçen süre üçü arasında etkili bir şekilde aynıdır, ki bu dikkat çekmeye değerdir: yanlış aşırı yükleme seçmek okuma işlemini daha ağır yapmaz, onu daha ağır yapar. Bellekte rahatça oturan bir iş, dosya büyüyene kadar veya konteynerin sınırı düşene kadar farkı hiç hissetmeyecektir.
Bir Çalışma Sayfası Nasıl Seçerim?
Sayfa seçiminde üç form vardır: sıfır tabanlı indeks, büyük/küçük harf duyarsız eşleşen tam sayfa adı veya StreamReadOptions örneği. Bilinmeyen bir sayfanın adı veya kapsama alanı dışındaki bir indeks ArgumentException hatası fırlatır.
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 TrySayfa argümanı hiç geçilmezse, sheetIndex varsayılan olarak 0 geçer. StreamReadOptions, sütunlar isim gerektiğinde baş satırlarını destekleyen tek yoldur, bu yüzden hemen ulaşın.
Yayın Akışı Öncesinde Sayfaları Nasıl Keşfederim?
WorkBook.GetSheetNames, iş defteri içeriğini yüklemeden iş defterindeki her sayfayı listeler. Sadece iş defterinin parça listesini okuduğu için, çok büyük bir dosya üzerinde bile ucuz kalır: 23.4 MB, 500,000 satırlık bir iş defterinde çeyrek saniye gibi bir sürede çalışır, ki bu bir kaç kilobaytlık bir dosyada aldığı süreyle aynıdır. Bu, düzenini önceden bilmediğimiz harici bir sistemden gelen bir dosya için doğal olarak ilk çağrıyı yapar.
Üç GetSheetNames aşırı yüklemesi, IReadOnlyList<string> döndüren hepsi
| Aşırı Yükleme | Kaynak |
|---|---|
GetSheetNames(string path) | Disk üzerindeki bir dosya |
GetSheetNames(Stream stream) | Açık bir akış |
GetSheetNames(byte[] data) | Bellekte bir tampon |
Döndürülen listedeki konum, StreamRows kabul ettiği sayfa indeksine eşittir, bu nedenle iki API doğrudan hizalanır: bu listedeki 2 indeksindeki sayfa, StreamRows(path, 2) okuduğu sayfadır.
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
NextSütun Adına Göre Satırları Nasıl Okurum?
HasHeaderRow ayarlandığında sütunları adlandırır ve başlık adına göre satırların okunmasına izin verir. Başlık satırı adlandırma için tüketilir ve veri olarak sunulmaz, ve HeaderRowIndex'den önceki herhangi bir satır atlanır, bu gerçek başlığın üzerinde bir başlık veya önsözün oturduğu yaygın bir durumu ele alır.
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 gerektirir. Olmadan, dize indeksleyicisi ve TryGetCell her ikisi de InvalidOperationException fırlatır.Başlık işleme kasıtlı olarak katıdır. Sayfa, yapılandırılmış HeaderRowIndex'da veya öncesinde bir satır içermezse, dizilim 'başlık satır bulunamadı' mesajıyla InvalidOperationException fırlatır, ve veri satırı başlık indeksini aşarsa hemen fırlatır. Bu, bir tüketicinin Take veya erken bir break kullanarak yanlış yapılandırmayı görmesi yerine sessizce hiçbir şey okumaması sağlar.
Sütun adı eşleşmesi büyük/küçük harf duyarsızdır ve çevresindeki beyaz space'i kırpar. Tekrarlanan başlık adları, ilk sol taraftaki eşleşen sütuna çözülür.
StreamReadOptions Ne Yapar?
StreamReadOptions özellikleri, nesne başlatıcı üzerinden ayarlanır
| Özellik | Tür | Default | Davranış |
|---|---|---|---|
SheetIndex | int | 0 | Sıfır tabanlı çalışma sayfası indeksi. SheetName ayarlandığında yok sayılır |
SheetName | string | null | Çalışma sayfası adı, büyük/küçük harf duyarlılığı yok. SheetIndex öncelik alır |
HasHeaderRow | bool | false | Doğru olduğunda, HeaderRowIndex'da satır sütunları adlandırır ve veri olarak sunulmaz |
HeaderRowIndex | int | 0 | Başlığa sahip sıfır tabanlı sayfa satırı. Öncesindeki satırlar atlanır |
Seçmeli Sütunları Nasıl Ele Alırım?
Adlandırılmış iki erişici, başlıkta olmadığı bir sütunu nasıl ele aldıklarında farklılık gösterir ve yanlış olanı seçmek tolere edilebilir bir kaynak dosyasını çökmeye dönüştürür. Dize indeksleyici ArgumentException fırlatır; TryGetCell false döndürür.
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 başlangıçta göründüğünden daha dar bir soruya yanıt verir: o durumda başlık sütun adını içeriyor mu der, diğer bir satıra burada bir değer var mı sorusunu sormaz. Bilinen bir sütunlu seyrek aralıklı bir satır, true ile null hücresi döndürür, bu yüzden çıkışta hala bir null kontrolü gerekir. Bazı kaynak dosyalarından eksik olabilir herhangi bir sütun için TryGetCell kullanın ve yalnızca sütun garantilidir dize indeksleyicisini kullanın.
Bir StreamRow ile Nasıl Çalışırım?
Bir StreamRow, dizilim sırasında üretilen bir satırdır. Pozisyonunu, aslında içerdiği hücreleri ve her iki pozisyonel ve adlandırılmış aramayı açığa çıkarır.
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 üyeleri, her iki pozisyonel ve adlandırılmış erişim
| Üye | Tür | Davranış |
|---|---|---|
RowNumber | int | Sıfır tabanlıdır. Excel satırı 1, RowNumber 0 |
Cells | IReadOnlyList<StreamCell> | Dağınık. Yalnızca içerik bulunan sütunlar mevcuttur |
Header | IReadOnlyList<string> | Sütun tarafından konumlanmış sütun adları, bu yüzden Header[i] sütunu i adlandırır. Boş bir başlık sütunu null ve Header kendisi, başlık yapılandırılmadığında null |
this[int columnIndex] | StreamCell | Sıfır tabanlı sütun indeksindeki hücre veya sık boşluk için null |
this[string columnName] | StreamCell | Adlandırılmış başlık sütununun altındaki hücre. Ad adı olmadığında ArgumentException fırlatır |
TryGetCell(string, out StreamCell) | bool | Başlık adını içerdiğinde true, etmediğinde false |
Header, StreamReadOptions.HasHeaderRow ayarlanmadıkça null olur. Yinelemeden önce onu koruyun, ya da döngü bir null listedeki atlayışları derecelendirir.Seyrekliğin özelliği, çağıran kodu şekillendirir. Bir satır sabit genişlikte bir kayıt değildir: A'dan F'ye sütunlarla bir sayfa, üç sütunun doldurulduğu üç hücre içeren satırlar üretir ve pozisyonel indeksleyici boşluklar için null döndürür. RowNumber'nın sıfır tabanlı olması, IronXL'nin geri kalanıyla tutarlıdır, burada sayısal indeksleyiciler sıfır tabanlıdır, A1 stili dize adresleri ise değildir.
Bir StreamCell'den Yazılmış Değerleri Nasıl Okurum?
Bir StreamCell, bir hücrenin değiştirilemez bir anlık görüntüsüdür. Normal bir Cell'dan farklı olarak, iş defteri tarafından desteklenmez ve bir değeri geri yazmak için kullanılamaz.
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 üyeleri, pozisyon, tür ve değeri kapsar
| Üye | Tür | Davranış |
|---|---|---|
ColumnIndex | int | Sıfır tabanlı sütun indeksi |
ColumnLetter | string | Elektronik tablo sütun harfi, örneğin "A", "C" veya "AA" |
Type | StreamCellType | Tutulan değerin türü. Bir formül hücresi için önbellekteki sonucun türü |
Value | object | Ham yazılı değer. Boş hücre için null |
Text | string | Excel'in gösterdiği gibi biçimlendirilmiş gösterim metni |
IsFormula | bool | Hücre bir formül içerdiğinde true |
Value kutulanmış, bu yüzden ne tür dönüştürdüğünü Type takip eder:
NumberbirdoubleverirStringbirstringverirBooleanbirboolverirDatebirDateTimeverirBlanknullverir
Type kontrol etmek Value'a dokunmadan önce, gerçek veriyle ayakta kalabilen bir ithalat ile 40,000. satırda bir hata fırlatmak arasında fark yaratır.
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
NextBurada iki alışkanlık önemlidir. İlki her indeksleyici erişimini null kontrol etmektir, çünkü satırlar seyrektir ve Value bir boş hücre için null'dır, bu yüzden her iki durum aynı kontrol üzerinde birleşir. İkincisi ise dökmek yerine dönüştürmektir: Value ham yazılı değeri tutar ve doğrudan ondan döküm yapmaya çalışan kod, yalnızca bir dosyada bir sütunun farklı şekilde saklandığı bir hata yerleştirir. Bunun yerine Text okumak, hedef bir dizi sütun olduğunda tamamen makuldür.
StreamCellType Ne Raporlar?
StreamCellType değerleri, tarafından bildirilen StreamCell.Type
| Değer | Bildirildiğinde |
|---|---|
Blank | Hücre hiçbir değer tutmaz. Value, null'ye eşittir |
Number | Hücre bir sayısal değer tutar |
String | Hücre metin tutar |
Boolean | Hücre TRUE veya FALSE tutar |
Date | Hücre, iş defterinin tarih sistemine uyan bir tarih tutar |
Error | Hücre, bir Excel hata değeri tutar |
Kasıtlı olarak Formula üyesi yoktur. Bir formül hücresi burada önbellekteki sonucunu tür rahatlıkla rapor eder, örneğin Number ve formül-olması IsFormula ile ayrı ayrı gösterilir. Bir formül durumunun enum tarayan hiç kimse bir formül durumu bulamayacak ve bu bir eksiklik yerine tasarım gereğidir.
Akış Okuyucusunun Sınırlamaları Nelerdir?
Bunları önceden bilmek en yaygın yanlış teşhislerin önlenmesini sağlar.
Yalnızca yol aşırı yüklemeleri gerçekten düşük bellek gerektirir. Bu, sayfadaki en önemli uyarıdır. Bir geliştirici, 400 MB yüklemeyi byte[] olarak geçirdiğinde, belleği izlediğinde ve özelliğin hatalı olduğu sonucuna vardığında tam olarak bunu vurmuştur.
Geriye kalan sınırlar tasarımla düzeltildi:
- Sadece okunabilir: Akış okuyucu değişiklik yapamaz veya kaydedemez. Düzenleme,
WorkBook.Loadanlamına gelir. - Sadece XLSX:
.xlsyoktur, şifreli iş defterleri yoktur, ve herhangi tür yazma yoktur. - Sadece ileri yönlü ve tek geçişli: Rastgele erişim ve geri sarma yoktur. Bir sayfada zıplamak isteyen kodlar
Loadarar. - Stil veya biçimlendirme nesneleri yok: Hücre görünüşü ifşa edilmez.
- Yalnızca önbellekteki formül sonuçları: Formül ifadesi ifşa edilmez ve hiçbir şey yeniden hesaplanmaz.
StreamRows hem de GetSheetNames, WorkBook.Load için olduğu gibi, yöntem çağrıldığında geçerli bir IronXL lisansı gerektirir.Daha ileri bir uyarı sınırlama ile davranış arasında oturur: bir yoldan düşük bellek okuması en iyi çabayla yapılır. Zip merkezi dizisi okunamayan bir iş defteri, paketi belleğe yüklemenin geri kalanına dönebilir.
Bir Akış İthalat Hattı Nasıl Kurarım?
Üretimi taşıyan model, tam boyutta ne kaynak ne de hedefin bellekte tutulmadığı, batarya yığınlarını besleyen bir akış okumasıdır.
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 InterfaceBatarya yığını bunu sağlar. Satırlar zamanla gelir, sabit boyutlu bir tampon içine birikip tampon dolduğunda veritabanına veya sıraya akar. Zirve belleği, satır sayısından ziyade batarya boyutuna bağlı olduğu için 5,000 satırlık bir dosya ile 5,000,000 satırlık bir dosya aynı şekilde işlenir.
Bozuk satırları atlamak yerine atmak, toplu ithalatlar için kasıtlı bir seçimdir. Yüz binlerce içinde hatası olan bir satır koşuyu durdurmamalı ve her kayda RowNumber kaydetmek, operatörlere kötü bir değeri bir kaynak dosyası hücresine izlemeleri için bir yol sağlar.
Hangi Özel Durumları Ele Almalıyım?
GetSheetNames, grafik sayfaları da dahil olmak üzere iş defterindeki her sayfayı döndürür. Bir grafik sayfası hiçbir satır tutmaz, bu yüzden indeksini StreamRows'ya geçirmek bir hata yerine boş bir sıra verir. Her sayfa indeksini döngüye alan kod bunu görecektir ve orada bir boş sonuç beklenir.
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
NextTarih hücreleri, Excel for Mac tarafından üretilen 1904 tabanlı iş defterleri de dahil olmak üzere iş defterinin tarih sistemine uyar. Çağrı kodunda bir ayarlama gerektiği yoktur.
Sırada Nereye Gitmeliyim?
StreamRows büyükçe bir XLSX dosyasıyla hızlı bir şekilde, bellek sabit kalan bir şekilde değerler almak için iyi işler. Değerleri okumayı aşan her şey, tam iş defteri modeline aittir ve aynı boru hattında ikisini birleştirmek normaldir. Doğrulama veya ithal etmek için yayınla, ardından düzenlemeler gerektiğinde daha küçük bir çalışma dosyasını Load.
Yakındaki işlevsellik için, C# Oku XLSX Dosyası nasıl yapılır standart okumayı kapsar, Excel Dosyalarını İçeri Aktar nasıl yapılır veri ithalat modellerini kapsar ve C#'ta Excel Dosyalarını Okuma eğitimi temelleri üzerinde çalışır. dosya boyutu sınırlarını keşfetme sayfası format seviyesinde satır ve sütun tavanlarını ele alır ve WorkBook API referansı tüm sınıfı belgeler.
Ahmad, C#, Python ve web teknolojilerinde sağlam bir temele sahip bir full-stack geliştiricidir. Gerçek dünyadaki uygulamalarda ölçeklenebilir yazılım çözümleri oluşturmaktan ve tasarım ile işlevselliğin nasıl buluştuğunu keşfetmekten derin bir ilgi duyar.