Multiple sheets and streaming writes
On this page
Choose an entry point for the source
| Source and output | Entry point | Retained state |
|---|---|---|
| One sheet, one operation | Excel.SaveAs / SaveAsAsync | Input enumeration and workbook state |
| Several sheets in one file | Sequential WriteSheet calls on one writer | Current sheet, shared strings and output buffers |
| A business API returns batches | WriteSheet for the first batch, then AppendSheet | Current batch, without building a combined list |
| Database or network yields async rows | WriteSheetAsync(IAsyncEnumerable<T>) | Current row and writer state; source resources span enumeration |
Write two sheets and verify the result
Use Excel.SaveAs(path, data) for one sheet. For multiple sheets, keep one writer: start a sheet, append its remaining batches, then start the next sheet. Install TExcel from quick start, put this program in Program.cs and run it.
using TExcel;
using (var writer = Excel.CreateWriter("report.xlsx"))
{
writer.WriteSheet(new[] { new DeviceRow { Code = "P-001", Name = "Inlet pump" } }, "Devices");
writer.AppendSheet(new[] { new DeviceRow { Code = "P-002", Name = "Outlet pump" } });
writer.WriteSheet(new[] { new { Code = "G-001", Name = "Pump group" } }, "Groups");
writer.Complete();
}
Console.WriteLine($"Sheets: {string.Join(", ", Excel.GetSheets("report.xlsx").Select(x => x.Name))}");
var devices = Excel.Query<DeviceRow>("report.xlsx", sheetName: "Devices").ToList();
Console.WriteLine($"Devices: {devices.Count}");
foreach (var device in devices)
{
Console.WriteLine($"{device.Code}: {device.Name}");
}
/// <summary>所有设备批次共享同一套导出列。</summary>
public sealed class DeviceRow
{
/// <summary>设备业务编码固定排在第一列。</summary>
[ExcelColumn("Code", Order = 0)]
public string Code { get; set; } = "";
/// <summary>设备名称固定排在第二列。</summary>
[ExcelColumn("Name", Order = 1)]
public string Name { get; set; } = "";
}Expected output:
Sheets: Devices, Groups
Devices: 2
P-001: Inlet pump
P-002: Outlet pumpGroups contains one group record. Running again overwrites report.xlsx. Names must contain 1–31 characters, exclude : \ / ? * [ ], and cannot start or end with an apostrophe. Duplicate names are checked without case sensitivity.
Append scope and completion
AppendSheet appends to the most recently written sheet without repeating headers. Keep the same row model and column order across batches, and finish appending before starting another sheet.
Appending reuses the current sheet’s entity-column metadata. Keep the same DTO across batches. Dictionary and column-collection paths do not establish the entity-column state required by AppendSheet<T>. Project dynamic rows to a stable DTO when appending, or supply a single continuous enumeration for that sheet.
This API operates on the output being created; it does not edit an arbitrary existing XLSX. Distinguish three stages:
WriteSheet/AppendSheetconsumes input and writes the current sheet.Complete/CompleteAsyncends the sheet and writes workbook metadata. Repeating completion or writing afterward throws.- Disposing the writer and ZIP archive finalizes the archive. Read, move or deliver afterward.
Dispose attempts to finish an incomplete workbook, so failure or cancellation may leave an openable partial file. Deliver only after writing, completion and disposal all succeed.
Keep a caller-owned stream open
This example uses MemoryStream to demonstrate ownership. It retains the complete compressed file, and ToArray() copies it again. Large exports can use file streams; see performance and large files.
using TExcel;
using var output = new MemoryStream();
using (var writer = Excel.CreateWriter(output, leaveOpen: true))
{
writer.WriteSheet(new[] { new { Code = "P-001" } }, "Devices");
writer.Complete();
}
output.Position = 0;
using (var reader = Excel.CreateReader(output, leaveOpen: true))
{
var row = reader.ReadSheetAsDictionary("Devices").Single();
Console.WriteLine($"Read back: {row["Code"]}");
}
Console.WriteLine($"Stream remains readable: {output.CanRead}");Expected output:
Read back: P-001
Stream remains readable: TrueDispose the writer before rewinding the seekable output. The reader also uses leaveOpen: true, so neither wrapper takes final ownership of output. The caller disposes it last. The default leaveOpen: false closes a supplied stream.
Write asynchronously
WriteSheetAsync accepts IEnumerable<T> or IAsyncEnumerable<T>, with matching append overloads. This complete program uses an async iterator: two rows create the sheet and two more append to it, without first constructing an input array.
For example, supply TORM’s ToAsyncEnumerable directly to avoid materializing the full database result. Keep the client alive throughout enumeration, pass cancellation to both sides, and finish reading the current sheet’s input before executing another command on the same client. For paged sources, load and append one batch at a time to the same writer.
The complete database-to-XLSX example includes SQLite initialization, filtering, a named projection and file verification.
using System.Runtime.CompilerServices;
using TExcel;
using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(30));
using (var writer = Excel.CreateWriter("async-devices.xlsx"))
{
await writer.WriteSheetAsync(ReadRowsAsync(1, 2), "Devices",
cancellationToken: cancellation.Token);
await writer.AppendSheetAsync(ReadRowsAsync(3, 2),
cancellationToken: cancellation.Token);
await writer.CompleteAsync();
}
Console.WriteLine($"Sheets: {Excel.GetSheets("async-devices.xlsx")[0].Name}");
var codes = Excel.Query<AsyncDeviceRow>("async-devices.xlsx", "Devices").Select(x => x.Code);
Console.WriteLine($"Async rows: {string.Join(", ", codes)}");
/// <summary>逐条生成示例行;实际项目在此使用数据库或网络异步来源。</summary>
static async IAsyncEnumerable<AsyncDeviceRow> ReadRowsAsync(
int start, int count, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
for (var number = start; number < start + count; number++)
{
cancellationToken.ThrowIfCancellationRequested();
await Task.Yield();
yield return new AsyncDeviceRow { Code = $"P-{number:000}" };
}
}
/// <summary>创建与追加使用同一类型,保持导出列稳定。</summary>
public sealed class AsyncDeviceRow
{
/// <summary>设备编码按文本保存。</summary>
[ExcelColumn("Code", Order = 0)]
public string Code { get; set; } = "";
}Expected output:
Sheets: Devices
Async rows: P-001, P-002, P-003, P-004EnumeratorCancellation accepts the consumer’s token. Pass it through to database or network operations.
Pass cancellation to write and append operations. CompleteAsync() has no cancellation parameter.
Use one writer sequentially; do not submit concurrent sheet writes to the same archive.
Batches and memory for paged sources
Write the header with the first batch, append later batches to the current sheet, and finish each batch before fetching another. Establish whether source paging can duplicate or omit rows under concurrent updates; the writer cannot repair inconsistent input.
Memory includes the current source batch, row buffers, workbook shared strings and target stream. Changing application batch size does not clear shared strings.
Time projection
TimeZone applies a fixed offset to DateTime. NamedTimeZone applies rules for each event date and takes precedence, making it appropriate for historical daylight-saving rules. Neither changes source entities.
This independent program converts a fixed +08:00 timestamp to UTC and reads back ISO text with an offset. Its result does not depend on today’s date:
using TExcel;
var occurredAt = new DateTimeOffset(2026, 1, 1, 8, 0, 0, TimeSpan.FromHours(8));
using (var writer = Excel.CreateWriter("times.xlsx"))
{
writer.NamedTimeZone = TimeZoneInfo.Utc;
writer.WriteSheet(new[] { new { OccurredAt = occurredAt } }, "Events");
writer.Complete();
}
var row = Excel.QueryAsDictionary("times.xlsx", "Events").Single();
Console.WriteLine(row["OccurredAt"]);
Console.WriteLine($"Source unchanged: {occurredAt.Offset == TimeSpan.FromHours(8)}");Expected output:
2026-01-01T00:00:00.0000000+00:00
Source unchanged: True| Source type | Current behavior |
|---|---|
DateTime with NamedTimeZone | Event-date conversion; Local first converts to UTC and Unspecified is treated as UTC |
DateTime with only TimeZone | Fixed offset, without historical daylight-saving rules |
DateTime without a zone setting | UTC values convert to server local time, so machines can produce different results |
DateTimeOffset | NamedTimeZone may convert the offset; fixed TimeZone does not apply to this branch; default output is ISO text |
A column format may replace the default with formatted text. Specify whether consumers need an instant, offset text or local display value. See column mapping and conversion.
Diagnose export problems
| Symptom | Check |
|---|---|
| A file exists but Excel cannot open it | Successful completion and disposal before delivery |
| An openable file is missing records | Source, cancellation and write outcomes; openability alone does not prove success |
| Appending targets the wrong sheet | The most recent WriteSheet before the append |
| No sheet is available for append | An entity sheet must be active; dictionary/column paths and completed writers cannot supply it |
| A stream is closed or reads as empty | leaveOpen, disposal order and seekable stream Position |
| Memory grows during streaming | Retained input, unique text, memory output and unbounded prefetch |