C#で非常に大きなExcelファイルを順次ストリーミング読み込みする方法

Ahmad Sohail
Ahmad Sohail
更新日: 2026年9月17日

数十万行に及ぶスプレッドシートでは通常の方法が通用しません。 WorkBook.Load はワークブックの完全なインメモリモデルを構築します。これにより編集、スタイリング、数式、ランダムアクセスが可能となり、400 MBのエクスポートが数分かかり、最初の値が読み込まれる前に数GBを消費することの理由でもあります。

IronXLの順次ストリーミングリーダー WorkBook.StreamRows は、値のみが必要な作業のために存在します。 ディスクから直接一行ずつ生成するので、ワークブックを物理化することなく、シートに何行あってもメモリ使用量が平坦に保たれます。

APIそのものよりも重要なのは分割点の位置を理解することで、誤った理解がこの機能を誤用する最大の要因です。 StreamRows は読み取り専用、XLSX限定、順方向のみ:大量の値を高速で抽出する専用レーンです。 編集、スタイリング、数式、グラフ、ランダムアクセス、非XLSX形式はすべてWorkBook.Loadの役割です。

注意してください: IronXL 2026.9.2以降が必要です。 それ以前のバージョンはStreamRowsを公開しておらず、コンパイルに失敗します。
クイックスタート:大きなXLSXファイルを1行ずつストリーミングする

ファイルパスにStreamRowsを指定し、結果を列挙してください。 内部的には、文字列パスのオーバーロードはワークブックの部分をディスクから遅延読み込みし、一度に1行だけを物理化します。これにより、任意に大きなシートでもメモリが平坦に保たれます。

  1. 1IronXL を NuGet Package Manager でインストールします

    PM > Install-Package IronXL.Excel

  2. 2このコード スニペットをコピーして実行します。

    foreach (StreamRow row in WorkBook.StreamRows("large-export.xlsx"))
        Console.WriteLine(row[0]?.Text);
  3. 3実際の環境でテストするためにデプロイする

    今日からご自身のプロジェクトでIronXLを使い始めるには、無料トライアルをお試しください。
    arrow pointer


StreamRows と WorkBook.Load の間でどれを選ぶべきですか?

分割はファイルサイズだけでなく、仕事のニーズによる問題です。 セルを再スタイルする必要がある50 MBのファイルはLoadに属します。 データベースに三つの列を押し込む必要がある500 MBのファイルはStreamRowsに属します。

ストリーミングリーダーとフルワークブックモデルを選ぶ

要件StreamRowsWorkBook.Load
大量の値の抽出、インポート、ETL、バリデーションはいはい(遅い)
編集または保存なしはい
スタイリング、フォーマットオブジェクトなしはい
数式の表現と再計算いいえ(キャッシュ結果のみ)はい
任意のセルへのランダムアクセスいいえ(順方向のみ)はい
XLS、CSV、TSV、暗号化ワークブックなしはい
グラフと画像なしはい

このギャップは仕事のデザインを変えるほど広いです。 23.4 MBのワークブックの500,000行すべてをストリーミングするのに約6秒かかり、75 MBほど保持し、最初の行は0.25秒で取得可能です; 同じファイルに対するWorkBook.Load は両方の点で劇的に重いです。 ハードウェアとワークブックの形状がこれらの数値を動かし、異常に広い行や重い共有文字列テーブルを持つワークブックではまた異なります。 データ読み込みパフォーマンスガイドは、書き側での同等のトレードオフをカバーしています。


ワークブックから行をストリーミングする方法

WorkBook.StreamRows はWorkBookの静的メソッドです。 ソースとワークシートを与え、返ってくるものを列挙してください。

入力

半百万行のトランザクションデータ、幅が8列、23.4 MBのディスク上のもの。 Excelは問題なく開きます; 問題はコードが全体をメモリに取り込もうとする時から始まります。

Excel showing a Transactions worksheet scrolled to row 250,000 of 500,000, with the frozen header row reading TxnId, Date, Sku, Description, Qty, UnitPrice, Region and Status
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);
    }
}

出力

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
Text

ループは固定された列セットではなくrow.Cellsを歩くので、一行ごとの各セル。 RowNumberはゼロベースなので、サンプルは出力をExcelの番号と一致させるために1を加えます。 ここではヘッダーは通常の行として到着します: StreamReadOptions が提供されていないため、TxnId と Date は列の名前付けではなく、行1のセル値として表示されます。

戻り値の型はIEnumerable<StreamRow>であり、重要な区別はシーケンスが反復されるまで何も読み込まれないことです。 行はループが進むにつれて一度に一つずつ生成されるため、500,000行のシートに対するforeachはメモリに一行だけ保持し、50万行ではありません。 その結果、シーケンスは単一パスかつ順方向のみであり、前の行に戻ることやその途中にインデックスを付けることはできません。 LINQオペレーターは通常通り合成されます。つまり、.Take(1000)は千行を読んでそこで止まります。

各 StreamRow にはコンテンツを持つセルのみが含まれます。これは、以下のStreamRow を操作するの項で説明されています。

どのオーバーロードを使ったほうがいいですか?

九つのオーバーロードが三つのソースと三つのワークシートを名付ける方法をカバーしています。 重要なのはソースです、なぜならstring pathオーバーロードのみがディスクから遅延読み込みするからです。 Stream と byte[] のオーバーロードは、読み取り中はパッケージの解凍された内容をメモリに保持する必要があります。

9つの StreamRows オーバーロードはすべて IEnumerable<StreamRow> を返します

オーバーロード低メモリ
StreamRows(string path, int sheetIndex = 0)はい
StreamRows(string path, string sheetName)はい
StreamRows(string path, StreamReadOptions options)はい
StreamRows(Stream stream, int sheetIndex = 0)なし
StreamRows(Stream stream, string sheetName)なし
StreamRows(Stream stream, StreamReadOptions options)なし
StreamRows(byte[] data, int sheetIndex = 0)なし
StreamRows(byte[] data, string sheetName)なし
StreamRows(byte[] data, StreamReadOptions options)なし

ファイルがすでにメモリ上にある場合、Stream と byte[] のオーバーロードは便利です。例えば、バッファリングされたアップロードなどです。 それらはまだ一行ずつストリームされ、完全なワークブックモデルを構築することは避けられますが、アンパックされたコンテンツは読み込みの全体にわたり存在します。 それはディスク上のファイルのサイズの約10倍を走ることが予想されるので、23.4 MBのワークブックはファイルサイズが示す値ではなく、約200 MB以上保持されます。 大きなファイルの場合はファイルパスを使用してください。

三つとも同一の行と合計を返します; コストはメモリであり、速度や正確さではありません

ソース経過ピークメモリー
string path6.3 s75 MB
Stream6.2 s309 MB
byte[]6.3 s291 MB

経過時間は三つすべてで実際に同一であるため注意が必要です:間違ったオーバーロードを選んでも読み取りが遅くなるわけではありませんが、重くなります。 メモリに快適に収まるジョブは、ファイルが成長するか、コンテナの制限が下げられるまで違いを全く感じないでしょう。

ワークシートの選び方

シート選択には三つの形式があります:ゼロベースのインデックス、大文字小文字区別なしに正確なシート名、またはStreamReadOptionsインスタンス。 未知のシート名または範囲外のインデックスは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);
}

シート引数を指定しない場合、最初のシートがストリームされます。これは sheetIndex が 0 をデフォルトとしているためです。 StreamReadOptionsだけがヘッダー行をサポートするルートであるため、列に名前が必要になるとすぐに手を伸ばす必要があります。


ストリーミング前にシートを発見する方法

WorkBook.GetSheetNamesはワークブックの内容を読み込むことなく、ワークブック順にすべてのシートを一覧表示します。 ワークブックの部分のリストだけを読み込むので、非常に大きなファイルでも安価です:23.4 MB、500,000行のワークブックで約四分の一秒であり、数キロバイトのファイルでも同じ時間を要します。 これはレイアウトが事前に知られていない外部システムから到着するファイルに自然なファーストコールとなります。

3つの GetSheetNames オーバーロードはすべて IReadOnlyList<string> を返します

オーバーロードソース
GetSheetNames(string path)ディスク上のファイル
GetSheetNames(Stream stream)オープンストリーム
GetSheetNames(byte[] data)インメモリバッファ

返されたリスト内の位置は StreamRows が受け入れるシートインデックスと等しく、したがって2つのAPIは直接一致します: このリストのインデックス 2 は 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);
    }
}

列名で行を読む方法

HasHeaderRowを設定することで列を命名し、ヘッダー名で行を読むことができます。 ヘッダー行は命名のために消費され、データとして提供されず、HeaderRowIndex以前の行はスキップされるため、タイトルや前書きが真のヘッダーの上に座っている一般的なケースを処理します。

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);
}
警告: 名前付きアクセスには HasHeaderRow が必要です。 それがないと、文字列インデックスおよび TryGetCell の両方が InvalidOperationException をスローします。

ヘッダー処理は意図的に厳格です。 シートに設定された HeaderRowIndex の前またはに列がない場合、列挙は「ヘッダ行が見つかりません」というメッセージで InvalidOperationException をスローし、データ行がヘッダインデックスを超えた時点でスローします。 これは、Take または早期の break を使用するコンシューマーが、何も読まないまま黙っているのではなく、誤設定をすぐに確認できるようにします。

列名の一致は大文字小文字を区別せず、周囲の空白をトリミングします。 重複したヘッダー名は最初の、左から最も一致する列に解決します。

StreamReadOptionsは何を設定するか?

オブジェクト初期化子によって設定されるStreamReadOptionsプロパティ

プロパティタイプDefault振る舞い
SheetIndexint0ゼロベースのワークシートインデックス。 SheetNameが設定されると無視されます
SheetNamestringnullワークシート名、大文字小文字を区別せずに一致します。 SheetIndexより優先されます
HasHeaderRowboolfalse真の場合、HeaderRowIndexの行が列名となり、データとして提供されません
HeaderRowIndexint0ゼロベースのシート行でヘッダーを保持します。 その前の行はスキップされます

オプションの列を扱う方法

二つの名前付きアクセッサーは、ヘッダーにない列をどのように扱うかが異なり、間違ったものを選ぶことが許容可能なソースファイルをクラッシュに変えます。 文字列インデクサーはArgumentExceptionをスローします; TryGetCell は 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);
    }
}

TryGetCellは見た目よりも狭い問題を回答します:これはヘッダーにその列名が含まれているかどうかを報告し、この特定の行に値があるかどうかではありません。 既知の列にスパースギャップがある行は、null セルを持つ true を返すため、出力時にはnullチェックが依然として必要です。 TryGetCellを使って、いくつかのソースファイルから欠落する可能性がある列に対して、文字列インデクサーは列が保証されている場合のみ。


StreamRowの扱い方

エナムレーション中に生成された1行がStreamRowです。 それはその位置、実際に含まれるセル、および位置による検索と名前付き検索の両方を公開します。

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)");
    }
}

位置によるおよび名前によるアクセスを持つStreamRowメンバー

メンバータイプ振る舞い
ゼロベースのRowNumberint Excel行1はRowNumber 0です
スパースのCellsIReadOnlyList<StreamCell>スパース。 コンテンツを持つ列のみが存在します
HeaderIReadOnlyList<string>列名は列で位置付けられ、したがって Header[i] は列 i を名前付けします。 空白のヘッダー列は null され、ヘッダーが設定されていない場合、Header 自体は null されます。
this[int columnIndex]StreamCellゼロベースの列インデックスのセル、またはスパースギャップ用のnull
名前付きヘッダー列の下のthis[string columnName]StreamCellセル。 名前がない場合はArgumentExceptionをスローします
TryGetCell(string, out StreamCell)boolヘッダーに名前が含まれている場合 true、含まれていない場合 false
警告: Header は null されますが、StreamReadOptions.HasHeaderRow が設定された場合は例外です。 それを反復する前にガードするか、ループはnullリストの参照解除を行います。

スパース性は呼び出しコードを形作る特性です。 行は固定幅のレコードではありません。列AからFまでがあるシートでは、三つの列が埋められると三つのセルを含む行を生成し、位置インデクサーはギャップにはnullを返します。 ゼロベースであるRowNumberはIronXLの他の部分と一致しており、数値インデクサーはゼロベースである一方、A1スタイルの文字列アドレスはそうではありません。


StreamCellから型付き値を読む方法

StreamCellは一つのセルの不変なスナップショットです。 通常のCellとは異なり、ワークブックによってサポートされておらず、値を書き戻すために使用することはできません。

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);
}

位置、タイプおよび値をカバーするStreamCellメンバー

メンバータイプ振る舞い
ColumnIndexintゼロベースの列インデックス
ColumnLetterstringスプレッドシートの列文字、例えば "A", "C", "AA"
TypeStreamCellType保持されている値の種類。 数式セルの場合はキャッシュされた結果の型
Valueobject生の型付き値。 空白セルのnull
TextstringExcelが表示する書式化された表示テキスト
IsFormulaboolセルが数式を含む場合true

Value はボックス化されているため、これを変換する対象は Type に従います:

  • Number は double を与えます
  • String は string を与えます
  • Boolean は bool を与えます
  • Date は DateTime を与えます
  • Blank は null を与えます

Value に触れる前に Type を確認することは、実際のデータが持ちこたえるインポートと、行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;
    }
}

ここで重要な二つの習慣があります。 最初のものは、すべてのインデクサーアクセスをnullチェックすることです。なぜなら、行がスパースで、Value が空白セルの場合、null だからです。したがって、両方のケースは同じチェックに収束します。 二つ目はキャストではなく変換することです:Valueが生の型付き値を保持し、そこから直接キャストするコードは列が異なる方法で格納されているファイルにだけ表面化するバグを教えます。 代わりにTextを読むことは、宛先が文字列列である場合は完全に合理的です。

StreamCellTypeが報告する内容

StreamCellType の値は StreamCell.Type によって報告されます

価値報告時
セルが値を保持していないBlank Value は null されます
Numberセルが数値を保持しているとき
Stringセルがテキストを保持しているとき
Booleanセルは TRUE または FALSE を保持します
Dateセルが日付を保持している、ワークブックの日付システムを尊重して
ErrorセルがExcelエラー値を保持しているとき

意図的にFormulaメンバーはありません。 数式セルは、例えば Number のように、そのキャッシュされた結果の実際のタイプをここで報告し、数式の有無は IsFormula を通じて別々に公開されています。 数式ケースのためのエナムをスキャンする人は見つけられないでしょう、それは設計からのものであり省略ではありません。


ストリーミングリーダーの制限事項

最も一般的な誤診を防ぐためにはこれらを最初から知っておくことが重要です。

パスのオーバーロードだけが本当に低メモリです。 これはページ上の最も重要な注意事項です。 400 MBのアップロードをbyte[]として渡し、メモリが上昇するのを見て、機能が壊れていると結論付ける開発者は、正にこれに当たるのです。

残りの境界はデザインによって固定されています:

  • 読み取り専用: ストリーミングリーダーは修正や保存ができません。 編集にはWorkBook.Loadが必要です。
  • XLSXのみ: .xlsはなく、暗号化ワークブックもなく、いかなる書き込みもありません。
  • 順方向のみおよび単一パス: ランダムアクセスも巻き戻しもありません。 シートをジャンプする必要のあるコードはLoadが欲しいでしょう。
  • スタイリングやフォーマットのオブジェクトなし: セルの外観は公開されていません。
  • ** キャッシュされた数式結果のみ:** 数式の表現は公開されておらず、何も再計算されていません。
注意してください: StreamRows と GetSheetNames の両方が有効なIronXLライセンスを必要とし、WorkBook.Load と同様にメソッドが呼び出されたときに適用されます。

制限と振る舞いの間にもう一つの警告があります:パスからの低メモリ読み取りはベストエフォートです。 zipの中央ディレクトリを読み取れないワークブックは、パッケージをメモリにロードすることに戻る可能性があります。


ストリーミングインポートパイプラインを構築する方法

製品の仕事を運ぶパターンは、ソースも宛先もフルサイズでメモリに保持されないようにバッチ書き込みをフィードするストリーミング読み取りです。

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);
}

バッチ処理がこれを支えている。行は一度に一つずつ到着し、固定サイズのバッファに蓄積され、バッファが一杯になったときにデータベースやキューにフラッシュします。 ピークメモリは行数ではなくバッチサイズによって制限されているため、同じコードで5000行のファイルと500万行のファイルを同じように扱います。

異常な行をスキップするのではなく、それを投げることは、バルクインポートのための意図的な選択です。 数十万行のうち解析できない行が一つあるからといって実行を中止すべきではなく、各レコードにRowNumberを記録することで、オペレーターは悪い値をソースファイルのセルにまで追跡できます。


どのエッジケースを処理すべきか?

GetSheetNamesはワークブック内のすべてのシートを返します、チャートシートも含む。 チャートシートは行を持っていないので、そのインデックスをStreamRowsに渡すと空のシーケンスを生成し、エラーは発生しません。 すべてのシートインデックスをループするコードはこれに直面し、そこでは空の結果が期待されます。

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);
    }
}

日付セルはワークブックの日付システムを尊重しており、Excel for Macが生成する1904ベースのワークブックも含みます。 呼び出しコードで調整は不要です。

次にどこに行くべきか?

StreamRowsは一つの仕事をよくカバーしています:大きなXLSXファイルから値を素早く取り出すことで、メモリが平坦に保たれます。 値を読むことを超えるものはフルワークブックモデルに属し、一つのパイプラインで両者を混ぜることは普通です。 ストリームして検証またはインポートし、編集が必要なときにLoadを使って小さな作業ファイルを処理してください。

C#でXLSXファイルを読む方法では標準の読み取りをカバーし、Excelファイルをインポートする方法ではデータインポートパターンをカバーし、C#でExcelファイルを読むチュートリアルでは基本を通じて説明します。 ファイルサイズ制限のトラブルシューティングページはフォーマットレベルの行と列の上限をカバーし、WorkBook APIリファレンスは完全なクラスを文書化しています。

Ahmadは、C#、Python、およびウェブ技術に強い基盤を持つフルスタック開発者です。彼はスケーラブルなソフトウェアソリューションの構築に深い関心を持ち、デザインと機能が実際のアプリケーションでどのように融合するかを探求することを楽しんでいます。

もっと読む

準備はできましたか?

NuGetダウンロード数 2,393,101バージョン:2026.11ちょうどリリースされました