Skip to Content
TExcelStream a database query to XLSX

Stream a database query to XLSX

On this page

This example passes a TORM IAsyncEnumerable<T> directly to TExcel to generate an XLSX as the database supplies rows. SQL filters and projects before export, so the application does not retain a complete query list. Output goes directly to a file, avoiding retention of the compressed file in a MemoryStream.

TExcel also accepts async sequences from other data access libraries or your application.

Create the project

The example uses .NET 10 and SQLite in memory, with no external database service:

dotnet new console -n DatabaseExportDemo -f net10.0 cd DatabaseExportDemo dotnet add package TORM dotnet add package TORM.Sqlite dotnet add package TExcel

Use matching TORM and TORM.Sqlite versions. Put this program in Program.cs and run dotnet run. It creates or overwrites device-export.xlsx in the current directory.

Complete program

using TExcel; using TORM; await using var db = new OrmClient(new ConnectionConfig { DatabaseType = DatabaseType.Sqlite, ConnectionString = "Data Source=:memory:", CommandTimeout = 30 }); await db.Ado.GetOpenedConnectionAsync(); await db.CodeFirst!.InitTableAsync<Device>(); await db.InsertableRange(new[] { new Device { Code = "0001", Name = "Inlet pump", Enabled = true }, new Device { Code = "0002", Name = "Outlet pump", Enabled = false }, new Device { Code = "0003", Name = "Spare pump", Enabled = true } }).ExecuteAsync(); using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(30)); var rows = db.Queryable<Device>() .Where(x => x.Enabled) .OrderBy(x => x.Id) .Select(x => new DeviceExportRow { Code = x.Code, Name = x.Name }) .ToAsyncEnumerable(cancellation.Token); using (var writer = Excel.CreateWriter("device-export.xlsx")) { await writer.WriteSheetAsync(rows, "Devices", cancellationToken: cancellation.Token); await writer.CompleteAsync(); } var exported = 0; foreach (var row in Excel.Query<DeviceExportRow>("device-export.xlsx", sheetName: "Devices")) { Console.WriteLine($"{row.Code}: {row.Name}"); exported++; } Console.WriteLine($"Rows exported: {exported}"); /// <summary>数据库中的设备记录,导出只取当前启用的业务字段。</summary> [OrmTable("export_devices")] public sealed class Device { /// <summary>数据库生成的主键,为导出提供确定的排序。</summary> [OrmColumn(IsPrimaryKey = true, IsIdentity = true)] public long Id { get; set; } /// <summary>设备编码按文本保存,避免丢失前导零。</summary> [OrmColumn(Length = 64, IsNullable = NullableState.Nullable)] public string Code { get; set; } = ""; /// <summary>设备的业务显示名称。</summary> [OrmColumn(Length = 128, IsNullable = NullableState.Nullable)] public string Name { get; set; } = ""; /// <summary>控制本例是否将该设备纳入导出。</summary> [OrmColumn(IsNullable = NullableState.Nullable)] public bool Enabled { get; set; } } /// <summary>只暴露工作表需要的两列,与数据库完整实体分离。</summary> public sealed class DeviceExportRow { /// <summary>第一列使用文本编码,读回时仍保留前导零。</summary> [ExcelColumn("Code", Order = 0)] public string Code { get; set; } = ""; /// <summary>第二列显示设备名称。</summary> [ExcelColumn("Name", Order = 1)] public string Name { get; set; } = ""; }

Expected output:

0001: Inlet pump 0003: Spare pump Rows exported: 2

Performance choices and resource lifetime

StageChoice and effect
DatabaseWhere, OrderBy and Select compose SQL before retrieval, returning only required rows and columns
InputToAsyncEnumerable defers retrieval until the writer consumes rows, avoiding a query result list
OutputOne writer generates the file directly, avoiding whole-file byte retention and a ToArray copy
Workbook stateShared strings and write buffers remain; memory still grows with unique workbook text

Keep the client alive for the entire input enumeration. A query reader may occupy its connection until WriteSheetAsync completes. Do not concurrently count, write logs or run another query on the same client. If a total is required, query it before export or use a separate client, and define consistency between that count and the exported data while records change.

GetOpenedConnectionAsync explicitly obtains an open connection, keeping this SQLite in-memory database alive; await using disposes the client at the end. Use the appropriate connection and transaction strategy for other databases. Streaming alone does not establish a business snapshot at one instant; see transactions and connection lifetime.

Slow output: finish a query batch before appending it

Direct streaming avoids a business-batch list, but its database reader waits with the output. To finish enumerating each query before writing its rows, advance by an increasing primary key. This example uses a manual Id > lastId predicate so it can project an export DTO. It is a separate path from TORM’s ToCursorPageAsync, which requires complete entities.

Insert the entire fragment before the first type declaration in the complete program above. It reuses db and adds one enabled device so the two-row batch size exercises an append. It writes device-export-batches.xlsx separately from the original file:

using var batchCancellation = new CancellationTokenSource(TimeSpan.FromSeconds(30)); var batchToken = batchCancellation.Token; await db.Insertable(new Device { Code = "0004", Name = "Cooling pump", Enabled = true }) .ExecuteAsync(batchToken); var batchSize = 2; var batches = 0; var batchRows = 0; long lastId = 0; using (var batchWriter = Excel.CreateWriter("device-export-batches.xlsx")) { while (true) { var page = await db.Queryable<Device>() .Where(x => x.Enabled && x.Id > lastId) .OrderBy(x => x.Id) .Take(batchSize) .Select(x => new BatchExportRow { Id = x.Id, Code = x.Code, Name = x.Name }) .ToListAsync(batchToken); if (page.Count == 0) break; if (batches == 0) await batchWriter.WriteSheetAsync(page, "Devices", cancellationToken: batchToken); else await batchWriter.AppendSheetAsync(page, cancellationToken: batchToken); batches++; batchRows += page.Count; lastId = page[^1].Id; Console.WriteLine($"Batch {batches}: {page.Count}"); if (page.Count < batchSize) break; } if (batches == 0) await batchWriter.WriteSheetAsync(Array.Empty<BatchExportRow>(), "Devices", cancellationToken: batchToken); await batchWriter.CompleteAsync(); } using var batchReader = Excel.CreateReader("device-export-batches.xlsx"); var header = batchReader.ReadSheetRows("Devices", hasHeader: false).First(); Console.WriteLine($"Headers: {string.Join(", ", header.Values)}"); Console.WriteLine($"Batch rows: {batchRows}, read back: {batchReader.ReadSheet<BatchExportRow>("Devices").Count()}"); /// <summary>携带续读主键,但只把业务编码和名称写入文件。</summary> public sealed class BatchExportRow { /// <summary>只用于本次导出推进主键边界,不出现在工作表中。</summary> [ExcelColumn(Ignore = true)] public long Id { get; set; } /// <summary>导出的第一列,与首批及所有追加批次保持同一结构。</summary> [ExcelColumn("Code", Order = 0)] public string Code { get; set; } = ""; /// <summary>导出的第二列,不读取数据库其他业务字段。</summary> [ExcelColumn("Name", Order = 1)] public string Name { get; set; } = ""; }

Additional output after the original program:

Batch 1: 2 Batch 2: 1 Headers: Code, Name Batch rows: 3, read back: 3

Each iteration creates a new query and completes ToListAsync before output begins. It advances lastId and fetches again only after writing succeeds. There is no total-count query or growing Skip. A short final batch ends the loop; an exact multiple of batchSize requires one additional query returning no rows. An empty result still creates a Devices sheet with headers.

The example assumes a unique, immutable positive integer Id and identical filters, authorization and ordering across batches. Gaps in keys are harmless; changing keys or predicates breaks this contract. Inserts, updates and deletes between queries can still change the result. Advancing by a key does not create a snapshot. Choose database isolation or a fixed export dataset when a consistent view is required.

ApproachData retained by the applicationDatabase reader and round trips
Direct ToAsyncEnumerableCurrent consumed row and library buffersOne query; reader spans file output
Key-based batches aboveBatch DTOs and library buffers, without accumulating all batchesOne query per batch; reader enumeration completes before that batch is written
Full ToListAsync firstAll export DTOsOne query; output begins after full materialization

All three retain shared strings and output state. Finishing a reader does not release this example’s connection keeping the in-memory database alive. Business batch size controls fetched objects; TExcel’s independent XML flush size controls write buffers. Small batches add round trips; large batches retain more objects.

Cancellation, failure and delivery

Pass cancellation to both query enumeration and worksheet writing. CompleteAsync() takes no cancellation argument and writes workbook metadata; disposing the writer finalizes the ZIP archive. Deliver a successful file only after writing, completion and disposal all succeed.

Use a separate temporary file for each download. On query, conversion or write failure, or cancellation, release resources and delete the incomplete file.

See streaming writes for other paginated sources and TORM queries for filters and projections.

lastId tracks this query’s position. This export is not resumable; recreating the writer creates a new file.