# Excel **Repository Path**: acl-software/Excel ## Basic Information - **Project Name**: Excel - **Description**: Excel Read-Write based on NPOI. - **Primary Language**: C# - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2025-05-15 - **Last Updated**: 2026-11-15 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Acl.Excel > A lightweight, high-performance Excel (`.xlsx`) read/write library for .NET. Directly implements the OpenXML (OOXML) spreadsheet format — **zero third-party Excel dependencies**. > > Full read/write pipeline built from scratch: **ZIP layer** — read bypasses `ZipArchive`/`DeflateStream` multi-layer wrapping; pure-managed `LibDeflateDecompressor` decompresses directly. Write assembles ZIP structure via `ZipArchive` + three selectable compression strategies. **XML layer** — read uses a custom `ByteSheetScanner` byte-stream scanner that parses XML bytes directly (bypasses `XmlReader`); write uses `Utf8RawWriter` direct byte emission (bypasses `XmlWriter`). > > Key technical highlights: **Zero-boxing expression-tree compilation** (`CellSetter` / `CompileRowWriter`, no boxing on read or write path) · **Pure-managed DEFLATE** (libdeflate C# port, zero P/Invoke, decompression 2-3× faster than .NET built-in) > Core value: single-pass streaming read + zero-DOM design deliver low-memory large-sheet I/O, combined with strict-skip filtering and lazy writes, built for "read-and-process-while-streaming" scenarios at million-row scale. --- ## Table of Contents - [1. Features](#1-features) - [2. Quick Start](#2-quick-start) - [3. Comparison with Other Excel Libraries](#3-comparison-with-other-excel-libraries) - [4. Core Concepts](#4-core-concepts) - [5. ExcelQueryOptions Reference](#5-excelqueryoptions-reference) - [5A. FluentQuery (Chained Queries)](#5a-fluentquery-chained-queries) - [6. Key IWorkbook Members](#6-key-iworkbook-members) - [7. Reading Capabilities](#7-reading-capabilities) - [8. Writing Capabilities](#8-writing-capabilities) - [9. Read Strategy and Write Strategy](#9-read-strategy-and-write-strategy) - [10. Type Mapping](#10-type-mapping) - [11. Source Generator (AOT / Zero Reflection)](#11-source-generator-aot--zero-reflection) - [12. Zero-Boxing Data Access (CellValue)](#12-zero-boxing-data-access-cellvalue) - [13. Performance and Best Practices](#13-performance-and-best-practices) - [14. Exceptions and Boundaries](#14-exceptions-and-boundaries) - [15. Security and Defense in Depth](#15-security-and-defense-in-depth) - [16. FAQ](#16-faq) - [17. Contributing](#17-contributing) - [18. Examples and Benchmarks](#18-examples-and-benchmarks) - [20. References](#20-references) - [21. License](#21-license) --- ## 1. Features | Feature | Notes | |---------|-------| | Zero third-party dependency | Built entirely on .NET built-ins; no NPOI / EPPlus / ClosedXML needed for I/O | | On-demand streaming read | Single-pass worksheet XML scan, row-by-row yield, no full-file load | | Strict-skip filtering | Row filter evaluated *before* mapping to model; non-matching rows allocate zero objects | | Lazy write | `Write` only marks dirty sheets; `Save` flushes to disk once | | Incremental persist | Unchanged sheets are byte-copied from original ZIP; only dirty sheets are rewritten | | Atomic write | Writes to a `.tmp` file first, then atomically replaces the original on success | | Source Generator (AOT) | `[Excel]` / `[ExcelColumn]` attributes generate precompiled read/write code at build time — zero reflection, zero `Expression.Compile`, fully AOT-compatible | | Zero-boxing data access | `CellValue` value-type struct (24B, explicit layout union) + `CellCategory` discriminator enum for direct type-safe value access | | Security depth defense | File-size guard, format validation, decompression-bomb guard, XXE disabled, ZipSlip filtering, control-character sanitization, shared-string table limit | | Multi-target | `net8.0` / `net10.0` | | Async API | `SaveAsync` / `SaveAsAsync` / `WriteAsync` | | Multiple output shapes | Strong-typed `TModel`, raw `object[]`, `DynamicEntitySet`, forward-only `DbDataReader` | | Adaptive read | Auto-switches between full materialization and streaming enumeration by estimated size to avoid OOM on large sheets | | Multi-sheet parallel write | Automatically parallelizes worksheet XML generation when sheet count ≥ 3 | | Pure-managed compression | LibDeflate C# port (zero P/Invoke), providing Balanced/Compression compression strategies | | Examples & benchmarks | `Acl.Excel.Examples` (23 scenarios) and `Acl.Excel.Benchmarks` (BenchmarkDotNet suite) | --- ## 2. Quick Start ### 2.1 Install ```bash dotnet add package Acl.Excel ``` The library references `Acl.Core` as a project dependency (built from the same source tree); the dependency is transitively propagated when published as a NuGet package. ### 2.2 Write + Read (closed loop) ```csharp using Acl.Excel; public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public decimal Price { get; set; } } // Write var products = new List { new() { Id = 1, Name = "Keyboard", Price = 99.9m }, new() { Id = 2, Name = "Mouse", Price = 49.5m }, }; ExcelFile.Write(products, "products.xlsx", "Products"); // Read (lazy enumeration, source file consumed only inside foreach) foreach (var p in ExcelFile.Query("products.xlsx", "Products")) { Console.WriteLine($"{p.Id}: {p.Name} @ {p.Price}"); } ``` ### 2.3 Model-to-column mapping By default columns are matched to model **property names** (case-insensitive). Property types are auto-converted: numeric columns → `int`/`decimal`/`double`, date columns → `DateTime`, boolean columns → `bool`. See [Section 10 Type Mapping](#10-type-mapping). --- ## 3. Comparison with Other Excel Libraries Acl.Excel differs fundamentally from EPPlus / NPOI / ClosedXML / MiniExcel: it is a **streaming I/O engine**, not an in-memory workbook model. The differences are described from two angles — design philosophy and performance/memory. ### 3.1 Design philosophy | Dimension | Acl.Excel | Typical in-memory workbook (EPPlus / NPOI / ClosedXML) | MiniExcel (streaming) | |-----------|-----------|--------------------------------------------------------|-----------------------| | Data residency | Disk streaming, single row released after flowing through | Entire workbook loaded into an in-memory object graph | Disk streaming | | Read model | `IEnumerable` lazy enumeration / `DbDataReader` | `Worksheet.Cells[row, col]` random access | `IEnumerable` lazy enumeration | | Write model | Mark dirty sheets + one-time flush | Resident in memory, explicit Save | Streaming write | | Large-sheet friendliness | Native million-row constant memory | Linear growth to GB-scale memory | Native | | Fine-grained random cell access | Not supported (streaming is inherently sequential) | Supported | Not supported | ### 3.2 Performance and memory The following are **architectural, qualitative** differences — not tied to any specific benchmark number: | Aspect | Acl.Excel | In-memory workbook library | |--------|-----------|----------------------------| | Row buffering complexity | O(1) single-row buffer (one `object[]` / `TModel` released after flowing through) | O(N) full DOM / object graph resident | | Million-row peak memory | Constant, depends only on row width | Grows linearly with row count, often GB-scale | | Parse engine | Default byte-level scanning (`ByteSheetScanner`, low allocation, malformed-XML tolerant); optional .NET `XmlReader` (`XmlReaderSheetScanner`) | Builds a complete XML DOM | | Write mode | Lazy write + one-time atomic flush | Resident in memory + explicit Save | | Decompression-bomb protection | XML-layer `MaxCharactersInDocument` / `MaxExpandedXmlChars` clamping | Depends on implementation | | Adaptive read | Built-in: small sheets auto-materialized (indexable/reusable), large sheets auto-streamed (constant memory) | Caller must paginate manually | On the adaptive threshold: the library switches between "full materialization" and "streaming enumeration" by estimated cell count (rows × columns) and a memory budget. Default memory budget is 256 MB; based on measured cell density, the threshold is roughly 6.3M cells for numeric-dominant data and 1.6M cells for string-dominant data (both @ 256 MB). Exceeding the threshold switches to streaming to avoid OOM. This logic is carried by `ExcelFile.QueryAdaptive` and `AdaptiveQueryOptions`. ### 3.2.1 Cross-library benchmark (raw data) The following are **BenchmarkDotNet measured raw data** (not estimates). Run conditions: - Dataset: 10,000 rows × 7 columns (`Id` / `Name` / `Price` / `Quantity` / `CreatedAt` / `IsActive` / `Category`); each library writes its own `.xlsx` then reads cross-library - Runtime: .NET 8.0.29 (X64 RyuJIT AVX2), command `dotnet run -c Release -f net8.0 -- bdnfull` - Config: `[MemoryDiagnoser]`, `warmupCount: 5`, `iterationCount: 20` - Comparison library versions: Acl.Excel (current source build) / NPOI 2.7.0 / MiniExcel 1.35.0 / ClosedXML 0.102.3 - Mapping convention: all four libraries uniformly mapped to `List` (TModel collection); type-conversion cost is consistent > BenchmarkDotNet summary table (Mean ± StdDev / single-run allocation): | Method | Mean | Error | StdDev | Gen0 | Gen1 | Gen2 | Allocated | |--------|------|-------|--------|------|------|------|-----------| | Acl.Excel Write | 13.35 ms | 0.132 ms | 0.152 ms | 31.25 | - | - | 462.07 KB | | NPOI Write | 184.72 ms | 7.228 ms | 8.323 ms | 10500.00 | 5000.00 | 1000.00 | 108164.66 KB | | MiniExcel Write | 27.49 ms | 0.448 ms | 0.516 ms | 3843.75 | 1156.25 | 1062.50 | 43497.80 KB | | ClosedXML Write | 173.27 ms | 8.351 ms | 9.282 ms | 18000.00 | 4000.00 | 2000.00 | 165894.97 KB | | Acl.Excel Read | 10.84 ms | 0.401 ms | 0.462 ms | 250.00 | - | - | 2350.47 KB | | Acl.Excel ReadSST | 16.23 ms | 0.546 ms | 0.629 ms | 593.75 | 281.25 | 62.50 | 5521.19 KB | | NPOI Read | 250.91 ms | 8.424 ms | 9.013 ms | 13000.00 | 10000.00 | 3000.00 | 111192.18 KB | | MiniExcel Read | 60.49 ms | 2.717 ms | 3.129 ms | 6500.00 | 1750.00 | 250.00 | 57787.68 KB | | ClosedXML Read | 355.36 ms | 15.836 ms | 18.237 ms | 25000.00 | 9000.00 | 2000.00 | 254541.57 KB | | NPOI ReadAcl | 210.68 ms | 4.546 ms | 5.052 ms | 11000.00 | 8500.00 | 2000.00 | 92845.16 KB | | MiniExcel ReadAcl | 61.83 ms | 3.454 ms | 3.977 ms | 8666.67 | 2000.00 | 333.33 | 78956.36 KB | | ClosedXML ReadAcl | 404.25 ms | 12.226 ms | 14.079 ms | 26000.00 | 9000.00 | 3000.00 | 261580.19 KB | | NPOI ReadAclSST | 232.87 ms | 13.299 ms | 15.315 ms | 12000.00 | 9000.00 | 3000.00 | 100550.48 KB | | MiniExcel ReadAclSST | 62.43 ms | 3.100 ms | 3.570 ms | 8250.00 | 2500.00 | 500.00 | 73826.62 KB | | ClosedXML ReadAclSST | 409.41 ms | 13.961 ms | 16.078 ms | 28000.00 | 11000.00 | 5000.00 | 253726.51 KB | > "ReadAcl" / "ReadAclSST" are third-party libraries reading Acl.Excel-written files (inlineStr / SST products) for interoperability verification; Acl.Excel's own reads are "Acl.Excel Read" / "Acl.Excel ReadSST". #### .NET 10 comparison (same conditions) The following is a `.NET 10.0.8` (X64 RyuJIT AVX2) rerun under identical conditions (otherwise identical to §3.2.1: 10K rows × 7 cols, `-c Release`, `warmupCount: 5`, `iterationCount: 20`): | Method | Mean | Error | StdDev | Gen0 | Gen1 | Gen2 | Allocated | |--------|------|-------|--------|------|------|------|-----------| | Acl.Excel Write | 11.47 ms | 0.189 ms | 0.218 ms | 31.2500 | - | - | 460.86 KB | | NPOI Write | 176.27 ms | 5.625 ms | 5.776 ms | 10500.0000 | 5500.0000 | 1500.0000 | 106014.85 KB | | MiniExcel Write | 24.06 ms | 0.964 ms | 1.111 ms | 3531.2500 | 1156.2500 | 1062.5000 | 40763.20 KB | | ClosedXML Write | 154.09 ms | 8.568 ms | 9.867 ms | 17333.3333 | 3000.0000 | 2000.0000 | 159322.96 KB | | Acl.Excel Read | 10.34 ms | 0.263 ms | 0.303 ms | 142.8571 | - | - | 2353.93 KB | | Acl.Excel ReadSST | 14.96 ms | 0.443 ms | 0.510 ms | 625.0000 | 312.5000 | 78.1250 | 5524.91 KB | | NPOI Read | 249.42 ms | 19.112 ms | 21.243 ms | 13000.0000 | 10000.0000 | 3000.0000 | 111339.20 KB | | MiniExcel Read | 50.85 ms | 1.814 ms | 2.089 ms | 5500.0000 | 1750.0000 | 250.0000 | 48412.75 KB | | ClosedXML Read | 269.18 ms | 4.326 ms | 4.443 ms | 24000.0000 | 9000.0000 | 2000.0000 | 246473.76 KB | | NPOI ReadAcl | 217.34 ms | 15.917 ms | 18.330 ms | 12000.0000 | 9000.0000 | 3000.0000 | 92754.88 KB | | MiniExcel ReadAcl | 49.05 ms | 3.692 ms | 4.252 ms | 7000.0000 | 1333.3333 | - | 65830.56 KB | | ClosedXML ReadAcl | 340.12 ms | 15.840 ms | 18.241 ms | 26000.0000 | 11000.0000 | 3000.0000 | 250965.85 KB | | NPOI ReadAclSST | 228.71 ms | 13.956 ms | 16.071 ms | 12000.0000 | 9000.0000 | 3000.0000 | 100610.14 KB | | MiniExcel ReadAclSST | 53.54 ms | 4.132 ms | 4.758 ms | 6666.6667 | 2000.0000 | 333.3333 | 61950.34 KB | | ClosedXML ReadAclSST | 360.87 ms | 9.825 ms | 11.315 ms | 26000.0000 | 11000.0000 | 4000.0000 | 245668.63 KB | > vs net8.0: Acl.Excel's own read/write times are roughly flat (write 13.35→11.47 ms, read 10.84→10.34 ms, net10 slightly faster); third-party libraries are generally faster on net10 (e.g. MiniExcel write 27.49→24.06 ms, ClosedXML read 355→269 ms), but the relative ranking and memory ratios across the four libraries are unchanged — Acl.Excel still leads across the board. ### 3.2.2 Detailed comparison and conclusions **Write (10K rows × 7 cols)** | Library | Time | vs Acl.Excel | Allocated | vs Acl.Excel | |----|------|------|----------|------| | Acl.Excel | 13.35 ms | 1× | 462 KB | 1× | | MiniExcel | 27.49 ms | 2.1× | 43,498 KB | 94× | | ClosedXML | 173.27 ms | 13.0× | 165,895 KB | 359× | | NPOI | 184.72 ms | 13.8× | 108,165 KB | 234× | Acl.Excel writes ~2× faster than MiniExcel and ~13–14× faster than ClosedXML / NPOI; allocation is only 1/94 – 1/359 of theirs. Gen0 count 31 vs several-thousand–ten-thousand, GC pressure is nearly negligible. **Read own format** | Library | Time | vs Acl.Excel | Allocated | vs Acl.Excel | |----|------|------|----------|------| | Acl.Excel (inlineStr) | 10.84 ms | 1× | 2,350 KB | 1× | | MiniExcel | 60.49 ms | 5.6× | 57,788 KB | 24.6× | | NPOI | 250.91 ms | 23.1× | 111,192 KB | 47.3× | | ClosedXML | 355.36 ms | 32.8× | 254,542 KB | 108× | Acl.Excel reads ~5.6× faster than MiniExcel, ~23× faster than NPOI, ~33× faster than ClosedXML; allocation is only 1/25 – 1/108 of theirs. **Interop (third-party libraries reading Acl.Excel products)** - Acl.Excel's inlineStr / SST `.xlsx` products can both be opened normally (zero exceptions) by NPOI / MiniExcel / ClosedXML — cross-library interoperability holds. - Among third-party readers, **MiniExcel is the most efficient**: ReadAcl 61.83 ms / 78,956 KB, ReadAclSST 62.43 ms / 73,827 KB, roughly 1/3.4 of NPOI's time and 1/6.5 of ClosedXML's. - **ClosedXML is the slowest and most allocating in every scenario** (ReadAcl 404 ms / 261 MB; ReadAclSST 409 ms / 254 MB). - Acl.Excel reading its own products (10.84 ms / 2,350 KB) is far faster than any third-party reader — no full object graph rebuild, direct streaming pass-through. **Conclusions** 1. Acl.Excel leads in **both time and memory** across "write / read / cross-library interop" scenarios, rooted in single-pass streaming + zero DOM + byte-level scanning + compile-time row mappers (no reflection, no boxing). 2. The memory advantage amplifies with dataset scale: at only 10K rows Acl.Excel already uses 1/25–1/359 the memory; at million rows in-memory workbook libraries grow linearly to GB-scale while Acl.Excel stays constant (see §3.2 qualitative analysis), making the gap orders of magnitude. 3. If interoperability with existing ecosystems is needed, Acl.Excel products can be consumed by NPOI / MiniExcel / ClosedXML; among them **MiniExcel is the optimal third-party read choice**. 4. Known deviation: in this environment Acl.Core is referenced as a Debug-built NuGet package, making Acl.Excel's absolute time slightly conservative; but the relative ranking and memory ratios across the four libraries are unaffected. ### 3.3 When to choose Acl.Excel - Reading/writing million-row data with constrained memory. - Read-and-process-while-streaming (ETL, import validation, report generation) without random cell access. - Zero third-party Excel dependency, pure managed, auditable. If the workload strongly depends on random cell-level read/write, rich styling / charts / formula engines, an in-memory workbook library is more suitable. --- ## 4. Core Concepts ### 4.1 Lazy workbook and micro-kernel `Workbook` is a lazy streaming implementation: reads are performed on demand via a single-pass stream, writes require `editable` mode and are persisted on `Save`. The public `IWorkbook` is a **micro-kernel** — it exposes only the irreducible performance-critical paths (3 query kernels + 2 write kernels + sheet management + persistence); convenience overloads and composition methods are provided via the `WorkbookExtensions` static class, keeping the interface stable and minimal. ### 4.2 Execution pipeline (read) All read entry points converge onto a two-layer kernel, then branch into three output shapes via the object-mapping layer (`DynamicEntitySet` is converted from `SheetDataReader`, not a separate path): ``` ┌──────────────────────── Read entry points ────────────────────────┐ │ ExcelFile.Query · workbook.Query │ │ workbook.QueryRaw · workbook.QueryDynamic │ │ workbook.OpenDataReader │ └───────────────────────────────┬──────────────────────────────────┘ ▼ SheetXmlReader (worksheet XML decode) ┌───────────────────────────┴───────────────────────────┐ │ Default Options.ReadStrategy=Fast: byte-level scan (ByteSheetScanner) │ │ Optional Options.ReadStrategy=Standard: .NET XmlReader parse │ └───────────────────────────┬───────────────────────────┘ ▼ cell decode (inlineStr / shared strings / formula result) ▼ ┌──────────────────── Object mapping layer (three outputs) ───────────────────┐ │ ① Raw workbook.QueryRaw → IEnumerable │ │ ② TModel workbook.Query → IEnumerable │ │ (CellSetter expression-tree compile, zero boxing) │ │ ③ SheetDataReader workbook.OpenDataReader → DbDataReader │ │ QueryDynamic converts to DynamicEntitySet via this │ └─────────────────────────────────────────────────────────────────────────────┘ ``` Key points: - All three paths share the same underlying decode; performance and memory characteristics are consistent. - `Query` maps via `CellSetter` expression-tree compilation (**zero boxing**); supports LINQ composition (`Where` / `OrderBy` / `GroupBy`), reading executes only when enumerated. - `QueryRaw` returns the most primitive `object[]` row sequence, for when you need full control over raw cell values. - `OpenDataReader` (SheetDataReader) pre-scans the first row to determine column names and types, then `Read()` streams forward, exposing a standard `DbDataReader` view (can feed `DataTable.Load`, ORMs, etc.). - `QueryDynamic` has no independent read path — it obtains row data via `SheetDataReader` and assembles it into a `DynamicEntitySet`. ### 4.3 Write pipeline ``` ExcelFile.Write / workbook.Write ▼ CompileRowWriter (expression-tree compile, zero-boxing write) ▼ Utf8RawWriter (byte-level direct worksheet XML write, no XmlWriter allocation) ▼ IZipEntrySink (compression strategy dispatch) ├─ Throughput → DotNetZipSink (.NET built-in deflate) ├─ Balanced → LibDeflateZipSink (pure-managed libdeflate, balanced) └─ Compression → LibDeflateZipSink (pure-managed libdeflate, max compression) ▼ Atomic persist (write .tmp first, replace on success) ``` ### 4.4 Adaptive read `ExcelFile.QueryAdaptive` auto-switches between "materialize into `List`" and "stream `IEnumerable`" by estimated cell count (rows × columns) and memory budget: - Small sheet: returns a materialized `List` that can be freely indexed, reused, and enumerated multiple times. - Large sheet: returns a lazy streaming enumeration, reading row-by-row without materializing the whole sheet, constant memory; the caller should consume while enumerating — calling `.ToList()` on it will still blow up memory. The estimated cell count is resolved by a lightweight `Workbook.GetSheetStats` scan by default (no value parsing, no `object[]` allocation); if the scale is known, pass it via `AdaptiveQueryOptions.EstimatedCells` to skip the scan. --- ## 5. ExcelQueryOptions Reference `ExcelQueryOptions` uniformly carries the window / header / mapping / filter semantics for all query entry points. All row and column numbers are 1-based. | Property | Type | Notes | |----------|------|-------| | `SheetName` | `string?` | Target sheet name; empty → first sheet | | `MaxRows` | `uint?` | Data row limit (**excluding header**); returns at most N data rows | | `MaxColumns` | `uint?` | Data column limit (NARROW contract); materializes only N columns from `StartColumn`, no padding outside window | | `StartRow` | `uint` | Start row number (≥1, default 1), physical start row; orthogonal to `HasHeader` | | `StartColumn` | `uint` | Start column number (≥1, default 1); NARROW column-window left anchor | | `HasHeader` | `bool` | Whether the first row is a header (default true) | | `EmptyHeaderReturnsEmpty` | `bool` | Return empty on empty header (default true) | | `MappingBuilder` | `ColumnMappingBuilder?` | Custom column mapping builder (overrides default name match) | | `RowFilterExpression` | `Delegate?` | Row-level filter (generic query: `Func`; dynamic query: `Func`) | | `Decompression` | `DecompressionStrategy` | Read-side decompression strategy, default `LibDeflate` | Fluent configuration (returns `this`): | Method | Purpose | |--------|---------| | `WithSheet(name)` | Set target sheet name | | `WithHeader(bool)` | Set whether header exists (default true) | | `WithMaxRows(int?)` | Set data row limit (excluding header) | | `WithMaxColumns(int?)` | Set data column limit (NARROW contract) | | `WithStartRow(int)` | Set start row (≥1) | | `WithStartColumn(int)` | Set start column (≥1) | | `WithMapping(builder)` | Set custom column mapping builder | | `WithFilter(predicate)` | Set row-level filter (TModel expression tree) | | `WithDecompression(strategy)` | Set read-side decompression strategy | Quick mapping configuration: ```csharp options.SetColumnNameMapping(m => m .Map("ProductName", x => x.Name) .Map("UnitPrice", x => x.Price)); options.SetColumnIndexMapping(m => m .Map(0, x => x.Id) .Map(1, x => x.Name)); ``` > Window contract: column window is **NARROW** (materialize only in-window columns, no padding, no `DBNull` fill); `MaxRows` / `MaxColumns` refer to data records / data columns, excluding the header. All public query entry points carry window parameters only via this type. --- ## 5A. FluentQuery (Chained Queries) `wb.Sheet("X")` returns a Fluent query builder, letting you configure options, filter, skip, and limit rows step by step: ```csharp // Basic usage foreach (var row in wb.Sheet("Products").Query()) Console.WriteLine(row[0]); // Typed foreach (var p in wb.Sheet("Products").Query()) Console.WriteLine(p.Name); // Options + filter + skip + limit var results = wb.Sheet("Products") .WithOptions(cfg => cfg.HasHeader(true).StartColumn(1).Columns(5) .EmptyHeader(false).Decompress(DecompressionStrategy.Deflate)) .Where(p => p.Price > 20) .Skip(2).Take(3) .Query() .ToList(); ``` **Chain order** (enforced at compile time): ``` Sheet → (WithOptions) → Where? → Skip/Take → Query / OpenDataReader / QueryDynamic ``` **WithOptions configuration**: | Method | Description | |------|------| | `HasHeader(bool)` | Whether first row is a header (default true) | | `StartColumn(int)` | Start column (1-based, default 1) | | `Columns(int)` | Max columns limit | | `EmptyHeader(bool)` | Return empty when header is empty (default true) | | `Decompress(strategy)` | Set decompression strategy | Typed WithOptions additionally supports `MapByName` / `MapByIndex`: ```csharp // Column name mapping (when column names differ from property names): wb.Sheet("Products") .WithOptions(cfg => cfg.MapByName(b => b .Map(p => p.Name, "ProductName") .Map(p => p.Price, "ProductPrice"))) .Query().ToList(); // Column index mapping: wb.Sheet("Products") .WithOptions(cfg => cfg.MapByIndex(b => b .Map(p => p.Id, 1) .Map(p => p.Name, 2) .Map(p => p.Price, 3))) .Query().ToList(); ``` **Skip / Take semantics**: last-wins, not cumulative or minimum: ```csharp wb.Sheet("X").Skip(2).Skip(1).Take(5).Take(3).Query() // Equivalent to Skip(1) + Take(3) ``` **Skip/Take vs StartRow/MaxRows**: | Aspect | `Skip`/`Take` (FluentQuery) | `StartRow`/`MaxRows` (ExcelQueryOptions) | |------|---------------------------|----------------------------------------| | Mechanism | Row filter (`RowFilterExpression`) | Window-level (skip during XML parsing) | | Skipped rows parsed? | Yes (all rows parsed, then filtered) | No (skipped at parse stage) | | Use case | Pagination with small offsets, combined with `Where` | Large-range skipping (e.g. skip first 10,000 rows) | | Performance | Higher overhead for large skips | Optimal for large-range skipping | > Column window (`StartColumn`/`Columns`) via `WithOptions` behaves identically to `ExcelQueryOptions`'s `StartColumn`/`MaxColumns` — both take effect during XML parsing. **Terminal methods**: | Terminal method | Return type | Description | |---------|---------|------| | `.Query()` | `IEnumerable` / `IEnumerable` | Deferred sequence, non-typed or typed | | `.OpenDataReader()` | `DbDataReader` | Streaming DataReader | | `.QueryDynamic()` | `DynamicEntitySet` | Dynamic entity set | --- ## 6. Key IWorkbook Members The `IWorkbook` micro-kernel members (convenience overloads in `WorkbookExtensions`): **Properties** | Member | Type | Notes | |--------|------|-------| | `FileName` | `string` | Workbook file name (with path) | | `SheetNames` | `string[]` | All sheet names (in file order) | | `HasChanges` | `bool` | Whether there are unsaved changes since last Save | | `DirtySheets` | `string[]` | Names of sheets changed since last Save | **Query kernels (three, each an irreplaceable low-level primitive)** | Member | Returns | Notes | |--------|---------|-------| | `Query(ExcelQueryOptions)` | `IEnumerable` | Generic query, `CellSetter` expression-tree compile (zero boxing) into lazy sequence | | `QueryRaw(ExcelQueryOptions)` | `IEnumerable` | Raw row query, lowest-level primitive | | `OpenDataReader(ExcelQueryOptions)` | `DbDataReader` | Read as a `DbDataReader` view; pre-scans first row for column names/types | **Write kernels (two)** | Member | Notes | |--------|-------| | `Write(IEnumerable, string, ColumnMappingBuilder?, bool append)` | Generic write, `CompileRowWriter` expression-tree compile (zero boxing) | | `Write(DynamicEntitySet, string, bool append)` | Write a `DynamicEntitySet` to the named sheet | **Sheet management & persistence** | Member | Notes | |--------|-------| | `RemoveSheet(name)` / `RenameSheet(old, new)` | Delete / rename a sheet (needs Save) | | `Save(CompressionStrategy)` / `SaveAs(file, CompressionStrategy)` | Save to file / save as new file | | `SaveAsync(...)` / `SaveAsAsync(...)` | Async save / async save-as | | `Close()` | Close the workbook, release resources | **Read strategy & guardrails (instance properties)** | Member | Type | Default | Notes | |--------|------|---------|-------| | `Options.ReadStrategy` | `ReadStrategy` | `Fast` | Read-side parse engine selection (see [Section 9](#9-read-strategy-and-write-strategy)) | | `Options.MaxSheetBytes` | `long` | 2 GB | Single-sheet part byte limit | | `Options.Options.MaxWorkbookBytes` | `long` | 1 MB | Whole-file size guard (prevent full-file-in-memory) | | `Options.Options.MaxSharedStringCount` | `int` | 1 000 000 | Shared string table entry limit | | `Options.SharedStringsMode` | `SharedStringsMode` | `Inline` | Write-side shared string mode | | `MaxExpandedXmlChars` | `long` | 1 GB | Decompressed XML expanded char total limit | | `EnablePathValidation` (static) | `bool` | `false` | Whether to normalize-validate the file path | | `WorkbookOptions.EnableCrossInstanceCache` (static) | `bool` | `false` | Cross-instance ZIP decompression cache toggle | --- ## 7. Reading Capabilities ### 7.1 Strong-typed query ```csharp // Static facade foreach (var p in ExcelFile.Query("data.xlsx", "Products")) { } // Delegate configuration foreach (var p in ExcelFile.Query("data.xlsx", o => o.WithSheet("Products").WithMaxRows(100).WithHeader(true))) { } // Workbook instance + row filter (pushed down to read layer, non-matching rows not mapped) using var wb = new Workbook("data.xlsx"); foreach (var p in wb.Query("Products", x => x.Price > 100)) { } ``` ### 7.2 Raw row query Raw row queries return `object[]` or `CellValue[]` directly, without mapping to model objects. Ideal when strong typing is not needed. #### QueryRaw (new array per row) ```csharp using var wb = new Workbook("data.xlsx"); foreach (object[] row in wb.QueryRaw(new ExcelQueryOptions { SheetName = "Raw" })) { // row[0], row[1], ... are raw cell values (object) } ``` #### QueryRawInto (buffer reuse, zero row-level allocation) ```csharp using var wb = new Workbook("data.xlsx"); var buffer = new object[16]; foreach (var row in wb.QueryRawInto(new ExcelQueryOptions { SheetName = "Raw" }, buffer)) { // ⚠️ row is the same reference as buffer; consume immediately within the iteration var name = row[0]?.ToString() ?? ""; } ``` #### QueryCellsInto (boxing-free, IWorkbook microkernel primitive) Returns `CellValue[]` (value-type struct), zero boxing per cell, memory allocation reduced by ~50%. This is the underlying implementation of `QueryRaw` / `QueryRawInto`. ```csharp using var wb = new Workbook("data.xlsx"); var buffer = new CellValue[16]; foreach (var cells in wb.QueryCellsInto(new ExcelQueryOptions { SheetName = "Raw" }, buffer)) { // ⚠️ cells is the same reference as buffer if (cells[0].Category == CellCategory.GeneralInt) long val = cells[0].AsInt64; // boxing-free value access } ``` ### 7.3 Dynamic query (DynamicEntitySet) ```csharp using var wb = new Workbook("data.xlsx"); DynamicEntitySet set = wb.QueryDynamic(o => o.WithSheet("Sheet1").WithHeader(true)); foreach (var row in set) { string name = (string)row["Name"]; // indexer returns dynamic int age = (int)row["Age"]; // or row.TryGetValue("Name", out dynamic v); } ``` ### 7.4 DataReader view ```csharp using var wb = new Workbook("data.xlsx"); using var reader = wb.OpenDataReader(new ExcelQueryOptions { SheetName = "Sheet1" }); var table = new System.Data.DataTable(); table.Load(reader); // standard DbDataReader interop ``` ### 7.5 Window and filter All read paths (`Query` / `QueryRaw` / `OpenDataReader`) share unified window parameters. **Row window:** - `StartRow`: physical row number of the first data row (≥1, default 1), orthogonal to `HasHeader` - `MaxRows`: maximum data record count (excluding header) **Column window (NARROW contract):** - `StartColumn`: left anchor of column window (≥1, default 1) - `MaxColumns`: column window width; materializes only in-window columns, no padding **Example:** ​```csharp // Start from row 3, take 5 records, columns B~D only var items = ExcelFile.Query("data.xlsx", o => o .WithStartRow(3) .WithMaxRows(5) .WithStartColumn(2) .WithMaxColumns(3)); ​``` **Row filter:** `RowFilterExpression` / `WithFilter` / `Query(sheet, predicate)`, pushed down to the read layer; unmatched rows never allocate model objects. --- ## 8. Writing Capabilities ### 8.1 Generic write (static facade) ```csharp ExcelFile.Write(products, "out.xlsx", "Products"); // Append to existing sheet ExcelFile.Write(more, "out.xlsx", "Products", append: true); // High-duplication text via shared strings, smaller file, faster write ExcelFile.Write(products, "out.xlsx", "Products", mode: SharedStringsMode.Auto); // Compression strategy ExcelFile.Write(products, "out.xlsx", "Products", strategy: CompressionStrategy.Balanced); ``` ### 8.2 Dynamic write ```csharp var set = new DynamicEntitySet(); set.AddMember("Name", typeof(string)); set.AddMember("Age", typeof(int)); set.Add(new object[] { "Alice", 30 }); set.Add(new object[] { "Bob", 25 }); ExcelFile.Write(set, "dynamic.xlsx"); ``` ### 8.3 Workbook instance write (multi-sheet / rename / delete) ```csharp using var wb = new Workbook("out.xlsx", editable: true); wb.Write(products, "Products"); wb.Write(orders, "Orders", append: false); wb.RenameSheet("Orders", "OrderList"); wb.RemoveSheet("Temp"); wb.Save(CompressionStrategy.Throughput); ``` ### 8.4 Shared string mode (SharedStringsMode) | Value | Notes | |-------|-------| | `Inline` (default) | Inline string (`t="inlineStr"`), lowest allocation on write path | | `Shared` | Force shared string table (`t="s"`); high-duplication text shrinks file | | `Auto` | Adapt by first-pass duplication rate (≥30% enables), bounded SST keeps memory controlled | --- ## 9. Read Strategy and Write Strategy ### 9.1 Read side: ReadStrategy Read-side decoding supports two modes controlled by a switch; `ReadStrategy` expresses only the "parse engine" axis: | Value | Notes | |-------|-------| | `Standard = 0` | Use .NET `XmlReader` (`XmlReaderSheetScanner`) to parse worksheet XML node by node | | `Fast = 1` (default) | Use the byte-level scanner (`ByteSheetScanner`) to scan the worksheet XML byte stream directly, low allocation, malformed-XML tolerant | **Decompression strategy**: By default, pure-managed `LibDeflateDecompressor` is used for direct decompression (`DecompressionStrategy.LibDeflate`, performance-optimal default; large deflate entry decompression throughput ≈ 2x of .NET built-in). You can switch to .NET built-in `DeflateStream` via either of the following: - **Global static strategy**: `SheetXmlReader.GlobalDecompression = DecompressionStrategy.Deflate;` (affects all queries) - **Per-query granularity**: `ExcelQueryOptions.Decompression = DecompressionStrategy.Deflate;` (only the current query) Setting it: ```csharp using var wb = new Workbook("data.xlsx"); wb.Options.ReadStrategy = ReadStrategy.Standard; // switch to XmlReader parse foreach (var p in wb.Query("Sheet1")) { } // Switch to .NET built-in DeflateStream (current query only) var opts = new ExcelQueryOptions { Decompression = DecompressionStrategy.Deflate }; foreach (var p in wb.Query("Sheet1", opts)) { } // Or via fluent API foreach (var p in wb.Query("Sheet1", new ExcelQueryOptions().WithDecompression(DecompressionStrategy.LibDeflate))) { } ``` ### 9.2 Write side: CompressionStrategy `CompressionStrategy` selects the compression implementation at `Save` / `ExcelFile.Write`: | Value | Implementation | Notes | |-------|----------------|-------| | `Throughput` (default) | `DotNetZipSink` | .NET built-in deflate (`CompressionLevel.Fastest`), throughput-first | | `Balanced` | `LibDeflateZipSink` | Pure-managed libdeflate (`Optimal`), throughput/ratio balanced | | `Compression` | `LibDeflateZipSink` | Pure-managed libdeflate (`SmallestSize`), max compression ratio | `CompressionStrategyFactory` centrally maintains the "strategy → implementation" mapping. Both sinks implement the internal `IZipEntrySink` interface, so write logic depends only on that abstraction and can switch seamlessly between .NET native and pure-managed libdeflate. `LibDeflateCompressor` is a pure-managed C# port of libdeflate — zero native / zero P/Invoke dependency. --- ## 10. Type Mapping ### 10.1 Column mapping priority chain `Query` and `Write` share a unified mapping resolution with the following priority: | Priority | Source | Description | |----------|--------|-------------| | ① Source generator | `TypeMappingRegistry` | AOT / zero reflection, compile-time | | ② User-defined `MappingBuilder` | Passed manually | Full control | | ③ `[ExcelColumn]` reflection | `TModel` marked `[Excel]` | Auto-detected, cached | | ④ Property name match | Property name = header | Fallback | ### 10.2 Default mapping (by property name) Models without attributes match header column names to **property names** (case-insensitive). Property types are auto-converted: - Numeric columns → `int` / `long` / `decimal` / `double` / `float` / `short` / `byte` - Date columns (with style detection) → `DateTime` / `DateTimeOffset` / `TimeSpan` - Boolean columns → `bool` - Text columns → `string` ### 10.3 `[ExcelColumn]` auto-mapping ```csharp [Excel] public class Product { [ExcelColumn(Name = "Product Name")] public string Name { get; set; } // Maps to "Product Name" column [ExcelColumn(Name = "Price")] public double Price { get; set; } // Maps to "Price" column public double Score { get; set; } // No attribute, matched by name "Score" } // No manual MappingBuilder needed — auto-detected var products = workbook.Query("Sheet1"); ``` ### 10.4 Custom mapping ```csharp // By column name var builder = ColumnMappingBuilder.ColumnNameMapping(m => m .Map("ProductName", x => x.Name) .Map("UnitPrice", x => x.Price)); ExcelFile.Query("data.xlsx", o => o.WithMapping(builder)); // By column position (NARROW-window friendly) var idxBuilder = ColumnMappingBuilder.ColumnIndexMapping(m => m .Map(0, x => x.Id) .Map(1, x => x.Name)); ``` ### 10.5 Conversion & fallback Cell values are converted to the target type via `Acl.Core`'s `Converter`. Numeric strings, texts with thousands/currency/percent styles, and date serial numbers (with style detection) are converted by semantics; unrecognizable text written into numeric properties falls back by target type (e.g. `default` or `0`). --- ## 11. Source Generator (AOT / Zero Reflection) Acl.Excel includes a built-in **Roslyn incremental source generator** that generates precompiled read/write code for model classes marked with `[Excel]`, eliminating runtime `Expression.Compile()` and reflection overhead, and **fully compatible with AOT compilation**. ### 11.1 Basic Usage Simply add `[Excel]` to your model class — `Workbook.Query` / `Write` automatically detect the registration and use the precompiled path. **No calling code changes required.** ```csharp using Acl.Excel; // 1) Mark the model [Excel] public class Employee { public string Name { get; set; } = ""; public int Age { get; set; } public double Salary { get; set; } public string Department { get; set; } = ""; public bool IsActive { get; set; } } // 2) Write — automatically uses precompiled path var employees = new[] { new Employee { Name = "Alice", Age = 30, Salary = 15000, Department = "Engineering", IsActive = true }, new Employee { Name = "Bob", Age = 25, Salary = 12000, Department = "Marketing", IsActive = true }, }; using (var wb = new Workbook("employees.xlsx")) { wb.Write(employees, "Sheet1"); wb.Save(); } // 3) Read — automatically uses precompiled path using (var wb = new Workbook("employees.xlsx")) { var list = wb.Query("Sheet1").ToList(); foreach (var e in list) Console.WriteLine($"{e.Name}, age {e.Age}, {e.Dept}, salary={e.Salary}"); } ``` ### 11.2 Generation Modes (`ExcelGenerate`) The `[Excel]` attribute accepts an `ExcelGenerate` parameter to control exactly which code the source generator produces for that type: ```csharp [Excel(ExcelGenerate.Read)] // Generate read code only (CellSetter[] + BuildFromHeaders) [Excel(ExcelGenerate.Write)] // Generate write code only (ColumnNames + WriteHeader + WriteRow) [Excel(ExcelGenerate.ReadWrite)] // Generate both read and write code (default) ``` | Scenario | Recommended Attribute | Notes | |----------|----------------------|-------| | Import DTO (read from Excel) | `[Excel(ExcelGenerate.Read)]` | Read-only; generated code is smaller | | Export model (write to Excel) | `[Excel(ExcelGenerate.Write)]` | Write-only; avoids generating unused read code | | Bidirectional (default) | `[Excel]` or `[Excel(ExcelGenerate.ReadWrite)]` | Most common; full read + write | **Read-only mode** (`ExcelGenerate.Read`) — importing data from Excel: ```csharp [Excel(ExcelGenerate.Read)] public class EmployeeDto { public string Name { get; set; } = ""; public int Age { get; set; } public double Salary { get; set; } } // Read uses precompiled path; Write falls back to runtime using var wb = new Workbook("employees.xlsx"); var list = wb.Query("Sheet1").ToList(); // ✅ precompiled ``` **Write-only mode** (`ExcelGenerate.Write`) — exporting data to Excel: ```csharp [Excel(ExcelGenerate.Write)] public class ReportRow { public string Product { get; set; } = ""; public int Quantity { get; set; } public decimal Revenue { get; set; } } // Write uses precompiled path; Read falls back to runtime var rows = GetReportData(); using var wb = new Workbook(); wb.Write(rows, "Report"); wb.Save("report.xlsx"); // ✅ precompiled ``` **Read-write mode** (`ExcelGenerate.ReadWrite`, default) — bidirectional scenario: ```csharp [Excel] // equivalent to [Excel(ExcelGenerate.ReadWrite)] public class Employee { public string Name { get; set; } = ""; public int Age { get; set; } } // Both read and write use precompiled paths using var wb = new Workbook("data.xlsx"); wb.Write(employees, "Sheet1"); // ✅ precompiled write var list = wb.Query("Sheet1").ToList(); // ✅ precompiled read wb.Save(); ``` ### 11.3 Custom Column Name Mapping Properties default-match Excel headers by **property name** (case-insensitive). Use `[ExcelColumn]` to specify a different column name: ```csharp [Excel] public class Student { [ExcelColumn("FullName")] // Excel column "FullName" → Name property public string Name { get; set; } = ""; [ExcelColumn("YearsOld")] // Excel column "YearsOld" → Age property public int Age { get; set; } public double Score { get; set; } // No attribute; auto-matches "Score" } ``` ### 11.4 Source Generator vs Expression-Tree Compilation The traditional `Query` path uses `Expression.Lambda.Compile()` to compile the mapping delegate **on first query**. Functionally equivalent, but two key differences: | Dimension | Traditional (expression-tree compiled) | Source Generator Precompiled | |-----------|---------------------------------------|------------------------------| | Code generation timing | First query via `Expression.Lambda.Compile()` | Compile-time (Roslyn) | | AOT compatible | No (depends on `Expression.Compile`) | Fully supported | | Write path | `Expression.Lambda` compiles `Func` | Compile-time generated `Action` delegate | > Both paths are identical in reflection, boxing, and column mapping (zero reflection, zero boxing, auto + `[ExcelColumn]`). The core advantages of the source generator are **compile-time determinism** and **AOT compatibility**. > Generated code auto-registers to `TypeMappingRegistry` at module initialization; `Workbook.Query` / `Write` uses it automatically with zero configuration. --- ## 12. Zero-Boxing Data Access (CellValue) `CellValue` is a 24-byte **value-type struct** (`record struct`) using explicit layout to implement a type-safe union, eliminating `object` boxing/unboxing overhead. ### 12.1 CellCategory Discriminator ```csharp public enum CellCategory : byte { Null, // Empty cell SharedString, // t="s" shared string Boolean, // t="b" boolean InlineString, // t="inlineStr" / t="str" inline string Error, // t="e" error value DateTime, // style=DateTime format TimeSpan, // style=Time format Percentage, // style=Percentage format GeneralInt, // General format parseable as integer GeneralDouble, // General format parseable as floating point GeneralString, // General format not parseable as number } ``` ### 12.2 CellValue Access ```csharp // cell.Category → CellCategory enum (zero-boxing discriminator) // cell.AsString → string? (valid only for SharedString/InlineString/GeneralString) // cell.AsInt64 → long (zero-boxing, valid only for GeneralInt) // cell.AsFloat64 → double (zero-boxing, valid only for GeneralDouble/DateTime/TimeSpan/Percentage) // cell.AsBoolean → bool (zero-boxing, valid only for Boolean) // CellValue.Null → static null singleton ``` ### 12.3 QueryCellsInto (internal optimization primitive) `QueryCellsInto` is a zero-boxing alternative to `QueryRaw`, returning `CellValue[]` instead of `object[]`: ```csharp using var wb = new Workbook("data.xlsx"); var options = new ExcelQueryOptions { SheetName = "Products", HasHeader = true }; var buffer = new CellValue[16]; // Pre-allocated buffer foreach (var row in wb.QueryCellsInto(options, buffer)) { // row and buffer are the same reference — consume immediately in iteration // CellCategory discriminator → zero-boxing type access if (row[1].Category == CellCategory.GeneralInt) totalQty += (int)row[1].AsInt64; else if (row[1].Category == CellCategory.GeneralDouble) totalQty += (int)row[1].AsFloat64; } ``` > `QueryCellsInto` and `QueryRawInto` are `internal` APIs for source generator and high-performance scenarios. External users should use `Query` (type-safe) or `QueryRaw` (dynamic access). --- ## 13. Performance and Best Practices 1. **Prefer lazy enumeration**: `ExcelFile.Query` returns `IEnumerable`, consumed row-by-row inside `foreach`; don't call `.ToList()` unnecessarily unless you truly need multiple enumerations or random access. 2. **Stream for large sheets**: at million-row scale use `Query` (or `QueryAdaptive` auto-switch) directly; avoid loading everything at once. 3. **Adaptive read**: use `QueryAdaptive` when scale is uncertain; when known, skip the estimation scan via `AdaptiveQueryOptions.EstimatedCells`. 4. **Source generator first**: add `[Excel]` to model classes for automatic precompiled paths, eliminating `Expression.Compile()` overhead and enabling AOT compilation. 5. **Compression trade-off**: default `Throughput` for write throughput; `Balanced` / `Compression` (pure-managed libdeflate, zero native dependency) for file size. 6. **High-duplication text**: write path `SharedStringsMode.Auto` / `Shared` significantly shrinks files and accelerates writes (SST bounded to 200k entries, memory可控). 7. **Column-window trimming**: when reading only some columns, use `WithStartColumn` + `WithMaxColumns` (NARROW) to reduce materialization and allocation. 8. **Push-down row filter**: `WithFilter` / predicate overloads push filtering down to the read layer, so non-matching rows allocate no model objects. 9. **Instance reuse**: when querying/writing the same file multiple times, reuse a single `Workbook` instance and `Save` / `Dispose` at the end, avoiding repeated opens. 10. **Incremental persist**: when modifying only some sheets, `Save` rewrites only dirty sheets; unchanged sheets are byte-copied from the original, minimizing I/O. --- ## 14. Exceptions and Boundaries | Exception / behavior | Trigger | |----------------------|---------| | `ArgumentException` | Empty file path, row/column number ≤ 0, file exceeds `Options.MaxWorkbookBytes` guard | | `InvalidDataException` | Not a valid xlsx (corrupt ZIP), shared string table exceeds `Options.MaxSharedStringCount`, XML expansion exceeds `MaxExpandedXmlChars` | | `FileNotFoundException` | Reading a non-existent file | | Empty collection returned | `EmptyHeaderReturnsEmpty=true` (default) returns empty on empty header instead of throwing | Reads and writes are streaming; a single cell/row exception is handled by the mapping-layer fallback and will not abort the whole-sheet read (unless a guardrail limit is hit). --- ## 15. Security and Defense in Depth | Defense | Notes | |---------|-------| | File-size guard | `Options.MaxWorkbookBytes` (default 1 MB) prevents full-file `CopyTo` into memory causing OOM | | Format validation | Validates ZIP structure and `Content_Types`, normalizes relationship `Target`, rejects illegal entries | | Decompression bomb | XML-layer `MaxCharactersInDocument` / `MaxExpandedXmlChars` clamp expansion scale | | XXE disabled | `XmlResolver = null`, external entity resolution forbidden | | ZipSlip filtering | Normalizes entry paths, filters `../` and out-of-bounds entry names | | Control-character sanitization | Sanitizes illegal XML control chars before write, preventing malformed XML | | Path validation | `EnablePathValidation` (static, default false) enables path normalize-validation when turned on | | Concurrency safety | Read kernel is locked, avoiding races when sharing a `Workbook` across threads | | Shared-string table limit | `Options.MaxSharedStringCount` (default 50,000, configurable) prevents malicious SST from exhausting memory; write-path SST bounded to 200k entries, falls back to inline on overflow | --- ## 16. FAQ **Q: Why does read return `IEnumerable` instead of `List`?** A: Lazy enumeration by default, streaming row-by-row with constant memory. Call `.ToList()` on the result if you need multiple enumerations. **Q: What is the difference between `Query`, `QueryCellsInto`, `QueryRaw`, `QueryDynamic` and `OpenDataReader`?** A: All five share the underlying decode but differ in output shape — `Query` strong-typed, `QueryCellsInto` zero-boxing `CellValue[]` (microkernel primitive), `QueryRaw` raw `object[]` (extension method built on `QueryCellsInto`), `QueryDynamic` dynamic entity set, `OpenDataReader` standard `DbDataReader`. Choose by consumption style. **Q: How do I access fields in dynamic read?** A: Via the indexer `row["ColumnName"]` (returns `dynamic`), or `row.TryGetValue("ColumnName", out dynamic v)`. **Q: The file didn't change after writing?** A: Writes require opening `Workbook` with `editable: true` and calling `Save` (or `ExcelFile.Write` already auto-Saves). Unsaved changes are not persisted. **Q: Large-sheet OOM?** A: Use `Query` (streaming) or `QueryAdaptive` (auto-switch); don't `.ToList()` huge result sets. **Q: How to control compression and file size?** A: `ExcelFile.Write(..., strategy: CompressionStrategy.Balanced/Compression)` or `workbook.Save(strategy)`; write path `SharedStringsMode.Auto` shrinks high-duplication-text files. --- ## 17. Contributing 1. Branch off the main branch for a feature. 2. Keep code style consistent (naming, indentation, XML comments). 3. New capabilities must ship with unit tests, green on both `net8.0` and `net10.0`. 4. Performance-related changes must be validated via `Acl.Excel.Benchmarks` (BenchmarkDotNet, `-c Release`) with no regression. 5. Ensure no compiler warnings before committing. --- ## 18. Examples and Benchmarks - `Acl.Excel.Examples`: 23 runnable scenarios (`dotnet run --project Acl.Excel.Examples []`) covering write, read, manual Workbook control, streaming read, conditional query, sheet-level query, range mapping, fill, multi-sheet, append, filter-writeback, async save, column metadata, error handling, security guard, batch processing, performance diagnostics, DataTable interop, data validation, **source generator**, QueryRawInto (buffer reuse), QueryCellsInto (zero-boxing). - `Acl.Excel.Benchmarks`: BenchmarkDotNet suite including cross-library read comparisons (NPOI / MiniExcel / ClosedXML reading Acl.Excel output), adaptive threshold benchmarks, and LibDeflate compression/decompression engine comparisons. - `Acl.Excel.Tests`: Unit and regression tests (net8.0 / net10.0 dual framework, 1500+ test cases). - `Acl.Excel.Tests`: unit and regression tests. --- ## 20. References - **[Acl.Excel vs MiniExcel 1.45.0: Million-Row Read/Write Benchmark](https://www.cnblogs.com/netcasewqs/p/22064907)** — Chinese-language technical blog post with detailed performance comparison under identical conditions (same dataset, same benchmark framework, same .NET version), including technical analysis and honest limitation disclosures. --- ## 21. License This project is published under the MIT License.