C#에서 전방향 스트리밍으로 매우 큰 Excel 파일 읽기

아흐마드 소하일
Ahmad Sohail
업데이트됨: 2026년 9월 17일

수백만 행이 있는 스프레드시트는 일반적인 접근 방식을 무너뜨립니다. WorkBook.Load은 워크북의 완전한 메모리 내 모델을 구축하여 편집, 스타일 지정, 수식 및 무작위 접근이 가능하게 하며, 이것이 400MB 내보내는 데 몇 분이 걸리고 첫 번째 값을 읽기 전에 몇 기가바이트를 소비하는 이유입니다.

IronXL의 전방향 스트리밍 리더 WorkBook.StreamRows은 값만 필요한 작업을 위해 존재합니다. 이것은 시트를 실현하는 대신 디스크에서 바로 한 행씩 제공하며, 이는 시트에 보관된 행의 수에 관계없이 메모리를 평면으로 유지합니다.

라인이 떨어진 곳이 API 자체보다 더 중요합니다. 왜냐하면 잘못 읽으면 그 기능이 잘못 사용되는 주요 원인이기 때문입니다. StreamRows은 읽기 전용, XLSX 전용, 전방향 전용으로, 대량 값 추출을 위한 빠른 통로입니다. 편집, 스타일 지정, 수식, 차트, 임의 접근 및 비-XLSX 포맷은 모두 WorkBook.Load의 작업으로 남습니다.

유의 사항: IronXL 2026.9.2 이상이 필요합니다. 이전 버전은 StreamRows을 노출하지 않으며 컴파일에 실패합니다.
빠른 시작: 대형 XLSX 파일을 행 단위로 스트리밍

StreamRows을 파일 경로에 지정하고 결과를 열거합니다. 백그라운드에서 문자열 경로 오버로드는 워크북의 부품을 디스크에서 느리게 읽으며, 한 번에 하나의 행만 실현되어 이를 통해 임의의 크기의 시트에도 메모리를 평면으로 유지합니다.

  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 사이에서 어떻게 선택하나요?

분할은 작업의 필요와 관련된 문제이며, 파일 크기만과는 관련이 없습니다. 셀의 스타일을 재조정해야 하는 50MB 파일은 Load에 속합니다. 데이터베이스에 세 개의 열을 푸시해야 하는 500MB 파일은 StreamRows에 속합니다.

스트리밍 리더와 전체 워크북 모델 간에 선택

요구 사항StreamRowsWorkBook.Load
대량 값 추출, 가져오기, ETL, 검증예예 (느림)
편집하거나 저장하기아니요예
스타일 지정, 객체 형식아니요예
수식 표현 및 재계산아니요 (캐시된 결과만)예
임의 셀에 대한 랜덤 접근아니요 (전방향 전용)예
XLS, CSV, TSV, 암호화된 워크북아니요예
차트 및 이미지아니요예

간격이 넓어서 작업 설계에 영향을 미칩니다. 23.4MB 워크북의 모든 500,000 라인을 스트리밍하는 데 약 6초가 걸렸으며, 약 75MB가 잡혔으며 첫 번째 행은 0.25초 만에 사용 가능했습니다. 같은 파일에서 WorkBook.Load는 두 경우에서 심각하게 무거워집니다. 하드웨어와 워크북 모양은 이 숫자에 영향을 미치며, 비정상적으로 넓은 행이나 무거운 공유 문자열 테이블을 가진 워크북은 다시 다르게 착륙합니다. 데이터 로딩 성능 가이드는 쓰기 측의 동등한 절충점을 다룹니다.


워크북에서 행을 어떻게 스트리밍하나요?

WorkBook.StreamRows은 WorkBook의 정적 메서드입니다. 소스와 워크시트를 제공하고 반환된 것을 열거합니다.

입력

거래 데이터의 50만 행, 8개의 열, 디스크에서 23.4MB. Excel에서는 문제가 없습니다; 문제는 코드를 사용하여 전체 내용을 메모리로 가져오려고 할 때 시작됩니다.

500,000행 중 250,000행까지 스크롤된 Transactions 워크시트와 TxnId, Date, Sku, Description, Qty, UnitPrice, Region, Status가 표시된 고정 헤더 행을 보여주는 Excel
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은 0 기반이므로, 샘플은 Excel의 자체 번호 매김과 정렬하기 위해 1을 더합니다. 여기서 헤더가 일반 행으로 도착함을 유의하십시오: StreamReadOptions이 제공되지 않으면, TxnId와 Date이 공유 열 1의 셀 값으로 들어오며 열 이름이 아닙니다.

반환 타입은 IEnumerable<StreamRow>이며, 중요한 차이점은 시퀀스가 반복될 때까지 아무것도 읽히지 않는다는 것입니다. 루프가 진행됨에 따라 행이 한번에 하나씩 생성되기 때문에, 500,000행의 시트를 가진 foreach에서 메모리에 들어오는 행은 하나의 행뿐이어서 50만 행이 메모리에 들어오는 것이 아닙니다. 따라서 시퀀스는 단일 패스와 전방향 전용입니다: 이전 행으로 돌아갈 수 없으며, 중간에 인덱스할 수 없습니다. LINQ 연산자는 일반적으로 이를 통해 조합되므로 .Take(1000)는 천 개의 행을 읽고 거기서 멈춥니다.

각 StreamRow는 내용이 있는 셀만 포함하며, 이는 아래의 StreamRow 작업에 포함됩니다.

어떤 오버로드를 사용해야 하나요?

아홉 가지 오버로드는 세 가지 소스와 세 가지 워크시트 명명 방식을 다룹니다. 소스 결정이 중요한데, 오직 string path 오버로드만 디스크에서 느리게 읽기 때문입니다. Stream와 byte[] 오버로드는 읽는 동안 패키지의 압축 해제된 내용을 메모리에 보관해야 합니다.

  • 모든 아홉 가지 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.4MB 워크북은 그 파일 크기에서 예상되는 것보다 조금 더 200MB를 넘습니다. 가장 큰 파일을 위해 파일 경로를 사용하십시오.

세 개 모두 동일한 행과 총계를 반환합니다; 비용은 속도나 정확성이 아닌 메모리에 있습니다

출처경과최고 메모리
string path6.3 초75 MB
Stream6.2 초309 MB
byte[]6.3 초291 MB

경과 시간은 세 개 간에 사실상 동일하며, 잘못된 오버로드를 선택한다고 해서 읽기가 느려지는 것이 아니라, 무거워진다는 점이 주목할 가치가 있습니다. 메모리에 잘 맞는 작업은 파일이 커지거나 컨테이너의 제한이 낮아질 때까지 차이를 전혀 느끼지 못할 것입니다.

어떻게 워크시트를 선택하나요?

시트 선택에는 세 가지 형식이 있습니다: 0 기반 인덱스, 대소 문자를 구분하지 않는 정확한 시트 이름, 또는 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.4MB, 500,000행 워크북에서는 매우 큰 파일에서도 이벤트를 유지합니다: 약 0.25초, 몇 KB 파일에서도 같은 시간입니다. 이는 레이아웃이 사전에 알려지지 않은 외부 시스템에서 도착한 파일의 자연스러운 첫 번째 호출이 됩니다.

모든 GetSheetNames 오버로드, 모든 IReadOnlyList<string>를 반환

오버로드출처
GetSheetNames(string path)디스크에 있는 파일
GetSheetNames(Stream stream)열린 스트림
GetSheetNames(byte[] data)메모리 버퍼

반환된 목록의 위치는 StreamRows가 수용하는 시트 인덱스와 같으므로 두 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행동
SheetIndexint00 기반 워크시트 인덱스. SheetName이 설정되면 무시
SheetNamestringnull워크시트 이름, 대소문자를 구분하지 않고 일치 SheetIndex보다 우선합니다
HasHeaderRowboolfalse참일 경우, HeaderRowIndex에서 행이 열의 이름을 지정하고 데이터로 제공되지 않음
HeaderRowIndexint00 기반 시트 행, 헤더 보유. 그 이전의 행은 건너뜁니다

선택적인 열을 어떻게 처리합니까?

두 가지 명명된 접근자는 헤더에 없는 열을 어떻게 처리하느냐에 따라 다르며, 잘못된 것을 선택함은 허용 가능한 소스 파일을 충돌로 바꿉니다. 문자열 인덱서가 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는 처음 나타난 것보다 좁은 질문에 답합니다: 이는 이 특정 행이 그곳에 값을 갖고있는지 여부가 아니라 헤더가 열 이름을 포함하는지 여부를 보고합니다. 알려진 열에서 희박한 간격이 있는 행은 true을 null 셀과 함께 반환하므로, 여전히 나가는 길에 null 검사가 필요합니다. 소스 파일의 일부에서 누락 될 수 있는 모든 열에 TryGetCell을 사용하고, 열이 보장된 경우에만 문자열 인덱서를 사용하십시오.


StreamRow와 어떻게 작업합니까?

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 구성원, 포지션과 명명된 접근을 함께

구성원유형행동
RowNumberint0 기반. Excel 행 1은 RowNumber 0입니다.
CellsIReadOnlyList<StreamCell>연속적이지 않습니다. 내용이 있는 열만 존재
HeaderIReadOnlyList<string>열 이름이 열로 정렬되어 있고, 그래서 Header[i]는 i을 이름으로 합니다. 빈 헤더 열은 null이며, Header 자체는 헤더가 구성되지 않았을 때 null입니다
this[int columnIndex]StreamCell0 기반 열 인덱스의 셀, 또는 희박한 간극을 위한 null
this[string columnName]StreamCell명명된 헤더 열 아래의 셀 이름이 없을 때 ArgumentException을 던집니다
TryGetCell(string, out StreamCell)bool헤더에 이름이 포함되어 있으면 true, 포함되어 있지 않으면 false
경고: Header는 StreamReadOptions.HasHeaderRow이 설정된 경우가 아니라면 null입니다. 반복하기 전에 보호하지 않으면 루프는 null 목록을 역참조합니다.

희박성은 호출 코드를 형성하는 속성입니다. 행은 고정 너비의 레코드가 아닙니다: A에서 F까지의 열이 있는 시트는 세 개의 열이 채워졌을 때 세 개의 셀을 포함하는 행을 생성하고, 포지션 인덱서는 간격에 대해 null를 반환합니다. RowNumber의 0 기반은 IronXL의 다른 부분과 일치하며, 숫자 인덱서는 0 기반이지만 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 구성원들

구성원유형행동
ColumnIndexint0 기반 열 인덱스
ColumnLetterstring스프레드시트 열 문자, 예를 들어 "A", "C" 또는 "AA"
TypeStreamCellType보유된 값의 종류입니다. 수식 셀의 경우 캐시된 결과의 유형입니다.
Valueobject원시 형식화된 값. 빈 셀에 대한 null
TextstringExcel이 사용하는 형식화된 표시 텍스트
IsFormulabool셀에 수식이 포함된 경우 true

Value은 박싱되어 있으므로, 그것을 무엇으로 변환하는지는 Type에서 따릅니다:

  • Number은 double을 제공합니다
  • String은 string을 제공합니다
  • Boolean은 bool을 제공합니다
  • Date은 DateTime을 제공합니다
  • Blank은 null을 제공합니다

Type를 확인한 후 Value를 다루는 것이 실제 데이터를 다루는 가져오기와 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를 통해 별도로 노출됩니다. 수식 경우를 위한 enum을 스캔하는 사람은 하나를 찾지 못할 것이며, 이는 설계상의 문제 일 뿐 누락된 것이 아닙니다.


스트리밍 리더의 제한은 무엇입니까?

이들을 미리 알고 있으면 가장 일반적인 오진을 방지할 수 있습니다.

오직 경로 오버로드만이 진정한 저 메모리입니다. 이는 이 페이지에서 가장 중요한 경고입니다. 400MB 업로드를 byte[]로 전달하고, 메모리가 올라가고, 기능이 고장났다고 결론짓는 개발자가 정확히 이것을 겪은 것입니다.

나머지 경계는 설계로 고정됩니다:

  • 읽기 전용: 스트리밍 리더는 편집이나 저장할 수 없습니다. 편집은 WorkBook.Load입니다.
  • XLSX 전용: .xls 없고, 암호화된 워크북도 없고, 어떤 종류의 쓰기도 없습니다.
  • 전방향 전용과 단일 패스: 무작위 접근과 되감기는 없습니다. 시트를 이동해야하는 코드는 Load을 원합니다.
  • 스타일이나 형식 객체 없음: 셀의 모양은 노출되지 않습니다.
  • 캐시된 수식 결과만: 수식 표현식은 노출되지 않으며 아무것도 다시 계산되지 않습니다.
유의 사항: 둘 다 StreamRows 및 GetSheetNames는 유효한 IronXL 라이선스를 필요로 하며, 메서드가 호출될 때 WorkBook.Load과 정확히 동일하게 적용됩니다.

하나의 추가적인 책망은 리미트와 행동 사이에 놓여 있습니다: 경로에서의 저 메모리 읽기는 최선을 다합니다. 중앙 디렉터리를 읽을 수 없는 지퍼된 워크북은 다시 패키지를 메모리에 로드할 수 있습니다.


스트리밍 가져오기 파이프라인을 어떻게 구축합니까?

생산 작업을 수행하는 패턴은 스트리밍 읽기가 배치된 쓰기로 공급되는 것이며, 출처나 목적지가 전체 크기로 메모리에 보관되지 않습니다.

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

여기서 얽히는 것은 배치입니다. 행은 한 번에 하나씩 도착하며, 고정 크기의 버퍼에 쌓이고 버퍼가 채워질 때 데이터베이스나 큐에 플러시됩니다. 최대 메모리는 행 수가 아닌 배치 크기에 의해 제한되므로, 동일한 코드는 5,000행 파일과 5,000,000행 파일을 동일하게 처리합니다.

자가구성된 행을 건너 뛰고 던지지 않는 것은 대량 가져오기를 위한 의도적인 선택입니다. 수백만 개의 행 중 하나의 분석 불가능한 행이 실행을 중단하지 않아야 하며, 각 레코드와 함께 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);
    }
}

날짜 셀은 Mac용 Excel이 생성하는 1904 기반 워크북을 포함해 워크북의 날짜 시스템을 준수합니다. 호출 코드에서는 조정이 필요 없습니다.

다음에 어디로 가나요?

StreamRows는 한 가지 작업을 잘 다룹니다: 큰 XLSX 파일에서 값을 빨리 가져오고, 메모리는 평면을 유지합니다. 값을 읽는 것 이상은 전체 워크북 모델에 속하며, 하나의 파이프라인에서 둘을 혼합하는 것은 정상입니다. 유효성 검사나 가져오기를 위해 스트리밍 한 다음, 편집이 필요할 때는 작은 작업 파일에서 Load을 사용하십시오.

주변 기능에 대해, C#에서 XLSX 파일을 읽는 방법은 표준 읽기를 다루고, Excel 파일 가져오기 방법은 데이터 가져오기 패턴을 다루며, C#에서 Excel 파일 읽기 튜토리얼은 기본을 다룹니다. 파일 크기 제한 문제 해결 페이지는 형식 수준의 행과 열 한계를 다루고 WorkBook API 레퍼런스는 전체 클래스를 문서화합니다.

아흐마드는 C#, Python 및 웹 기술에 탄탄한 기반을 갖춘 풀스택 개발자입니다. 그는 확장 가능한 소프트웨어 솔루션 구축에 깊은 관심을 가지고 있으며, 실제 응용 프로그램에서 디자인과 기능이 어떻게 조화를 이루는지 탐구하는 것을 즐깁니다.

더 읽기

시작할 준비 되셨나요?

NuGet 다운로드 수 2,393,101버전:2026.11방금 출시