Skip to Content
TExcelImport validation example

Import validation example

On this page

Generate an XLSX containing a duplicate identifier, then validate the archive, header and individual rows. The example preserves leading zeros, reports worksheet row numbers and stops before persistence when validation fails.

Create the project

dotnet new console -n ImportDemo -f net10.0 cd ImportDemo dotnet add package TExcel dotnet add package TUtility.Core

ImportPreviewListOutput<T> comes from TUtility.Core. It carries preview data but does not validate it automatically. See import preview models for its fields.

Generate and validate a file

Save this as Program.cs and run dotnet run. The application requires a Code, Name header, text identifiers and case-sensitive Ordinal uniqueness. These are application rules.

using TExcel; using TUtility; Excel.SaveAs("device-import.xlsx", new[] { new DeviceImportRow { Code = "0001", Name = "Pump A" }, new DeviceImportRow { Code = "0001", Name = "" }, new DeviceImportRow { Code = "0003", Name = "Pump C" } }, sheetName: "Devices"); using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(30)); var preview = await PreviewAsync("device-import.xlsx", cancellation.Token); Console.WriteLine($"Rows={preview.DataCount}; Candidates={preview.Data.Count}; HasError={preview.HasError}"); foreach (var result in preview.Results) Console.WriteLine($"Row {result.Row}: {result.Success} {result.ErrorMessage}".TrimEnd()); if (preview.HasError) Console.WriteLine("Preview contains errors; no data was saved."); /// <summary>完整扫描并返回候选,文件与 reader 均在返回前释放。</summary> async Task<ImportPreviewListOutput<DeviceImportRow>> PreviewAsync(string path, CancellationToken token) { using var content = File.OpenRead(path); if (content.Length > 32L * 1024 * 1024) throw new InvalidDataException("Upload exceeds 32 MiB."); await ExcelArchiveValidator.ValidateAsync(content, new ExcelArchiveLimits( Entries: 2000, EntryBytes: 64L * 1024 * 1024, ExpandedBytes: 256L * 1024 * 1024, CompressionRatio: 200), token); using var reader = Excel.CreateReader(content, leaveOpen: true); using var rows = reader.ReadSheetRows("Devices", hasHeader: false, cancellationToken: token, includeCellFacts: true).GetEnumerator(); if (!rows.MoveNext() || rows.Current.Values.Length != 2 || rows.Current.Values[0]?.ToString() != "Code" || rows.Current.Values[1]?.ToString() != "Name") throw new InvalidDataException("Expected the Code and Name header columns."); var result = new ImportPreviewListOutput<DeviceImportRow>(); var seen = new Dictionary<string, int>(StringComparer.Ordinal); while (rows.MoveNext()) { var row = rows.Current; if (++result.DataCount > 10_000) throw new InvalidDataException("Import exceeds 10000 data rows."); var errors = new List<string>(); var code = row.Values.ElementAtOrDefault(0)?.ToString() ?? ""; var name = row.Values.ElementAtOrDefault(1)?.ToString() ?? ""; var codeCell = row.Cells.FirstOrDefault(cell => cell.Column == 1); if (row.Values.Length > 2) errors.Add("Unexpected extra columns."); if (row.Cells.Any(cell => cell.HasFormula)) errors.Add("Formulas are not allowed."); if (string.IsNullOrWhiteSpace(code)) errors.Add("Code is required."); else if (codeCell.Type is not ("s" or "inlineStr")) errors.Add("Code must be stored as text."); else if (!seen.TryAdd(code, row.Number)) errors.Add($"Code duplicates row {seen[code]}."); if (string.IsNullOrWhiteSpace(name)) errors.Add("Name is required."); var success = errors.Count == 0; result.Results.Add(new ImportPreviewResult(row.Number, success, string.Join(" ", errors))); result.HasError |= !success; if (success) result.Data.Add(new DeviceImportRow { Code = code, Name = name }); } return result; } /// <summary>预检通过后的候选设备,列名与模板保持一致。</summary> public sealed class DeviceImportRow { /// <summary>设备身份必须作为文本读写,以保留前导零。</summary> [ExcelColumn("Code", Order = 0)] public string Code { get; set; } = ""; /// <summary>应用要求非空的设备名称。</summary> [ExcelColumn("Name", Order = 1)] public string Name { get; set; } = ""; }

Expected output:

Rows=3; Candidates=2; HasError=True Row 2: True Row 3: False Code duplicates row 2. Name is required. Row 4: True Preview contains errors; no data was saved.

DataCount counts input data rows; Data contains valid candidates. They can differ. This example retains all row results. Large imports need a detail limit or batching rather than unbounded candidate and error accumulation.

Why raw rows are useful

The typed conversion callback does not provide complete row and column locations. ReadSheetRows provides worksheet row numbers, positional values and cell facts:

CheckInputPrevents
Fixed headerFirst row’s ValuesWrong template or column order
Text identityExcelCell.Type, decoded ValuesNumeric cells losing leading zeros or long-ID precision
FormulaHasFormulaTreating stale cached formula values as original input
File duplicatesIdentifier-to-row dictionaryA later row silently replacing an earlier row
Required fieldsDecoded textTechnically convertible but incomplete business data

RawValue can be an index into the shared-string table. This example uses decoded Values for text and Cells for format facts. Do not substitute RawValue for all cell text.

Commit every batch after validation

Add TORM and TORM.Sqlite to the same project and add using TORM; at the top of Program.cs. Keep the complete program above and insert the following code before the DeviceImportRow declaration. Both the new ImportDevice and the original type must follow all top-level statements.

dotnet add package TORM dotnet add package TORM.Sqlite

Two new files pass through the same PreviewAsync: the first commits; a later batch in the second hits a database identifier conflict and rolls back earlier writes. The database and exception filter are SQLite-specific; the in-memory database is released on exit.

await using var db = new OrmClient(new ConnectionConfig { DatabaseType = DatabaseType.Sqlite, ConnectionString = "Data Source=:memory:" }); await db.CodeFirst!.InitTableAsync<ImportDevice>(); Excel.SaveAs("device-valid.xlsx", new[] { new DeviceImportRow { Code = "0001", Name = "Pump A" }, new DeviceImportRow { Code = "0003", Name = "Pump C" } }, sheetName: "Devices"); var valid = await PreviewAsync("device-valid.xlsx", cancellation.Token); Console.WriteLine($"Committed: {await CommitAsync(db, valid, cancellation.Token)}"); Excel.SaveAs("device-conflict.xlsx", new[] { new DeviceImportRow { Code = "0005", Name = "Pump E" }, new DeviceImportRow { Code = "0001", Name = "Existing code" } }, sheetName: "Devices"); var conflict = await PreviewAsync("device-conflict.xlsx", cancellation.Token); try { await CommitAsync(db, conflict, cancellation.Token, batchSize: 1); } catch (Microsoft.Data.Sqlite.SqliteException ex) when (ex.SqliteErrorCode == 19) { Console.WriteLine("Database conflict; entire import rolled back."); } var count = await db.Queryable<ImportDevice>().CountAsync(cancellation.Token); var partial = await db.Queryable<ImportDevice>().Where(row => row.Code == "0005").AnyAsync(cancellation.Token); Console.WriteLine($"After conflict: {count}; Code 0005 exists: {partial}"); /// <summary>使用服务端候选,在单个业务事务内顺序执行所有批次,提交成功才返回数量。</summary> async Task<int> CommitAsync(OrmClient client, ImportPreviewListOutput<DeviceImportRow> candidate, CancellationToken token, int batchSize = 400) { if (candidate.HasError || candidate.Data.Count == 0) throw new InvalidOperationException("A nonempty valid preview is required."); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(batchSize); return await client.UseTranAsync(async () => { var affected = 0; foreach (var batch in candidate.Data.Chunk(batchSize)) { var entities = batch.Select(row => new ImportDevice { Code = row.Code, Name = row.Name }).ToArray(); affected += await client.InsertableRange(entities).ExecuteAsync(token); } return affected; }, cancellationToken: token); } /// <summary>以文本编码主键约束新增导入的唯一性,保留前导零。</summary> [OrmTable("import_devices")] public sealed class ImportDevice { /// <summary>数据库主键兜底预检之后仍可能出现的并发编码冲突。</summary> [OrmColumn(IsPrimaryKey = true)] public string Code { get; set; } = ""; /// <summary>文件预检要求非空,数据库可空声明按当前映射合同显式配置。</summary> [OrmColumn(IsNullable = NullableState.Nullable)] public string Name { get; set; } = ""; }

In addition to the first program’s output, expect:

Committed: 2 Database conflict; entire import rolled back. After conflict: 2; Code 0005 exists: False

This CommitAsync consumes a candidate validated by the current process. It is not a controller accepting candidate arrays from a browser. The example supports creation only and enforces identifier uniqueness with a text primary key. Other providers require their own collation, case-sensitivity and constraint-error handling.

Batch size, memory and lock duration

  • Chunk(400) bounds current batch allocations; preview.Data retains all candidates, capped here at 10,000 data rows.
  • Each batch calls InsertableRange, avoiding per-row query-before-insert operations. Command count and suitable batch size depend on the provider.
  • All batches write sequentially inside one outer UseTranAsync; later failure rolls back earlier writes. Do not write concurrently on the same client.
  • Decompression, scanning and candidate construction happen before the transaction. If the application checks database references or permissions, recheck them inside the commit transaction.
  • Per-row results can use bounded summaries, with a separate candidate-storage limit. Response pagination does not bound candidate memory.

See TORM transactions for transaction boundaries and database streaming export for the reverse workflow.

Connect upload and commit

Pass the actual uploaded file through the same validation process, enforcing budgets on the server. Archive errors, template errors and exceeded limits fail the whole preview; row errors carry precise locations. Enumerate while both the reader and stream remain alive.

At commit time, verify the user, realm, file identity and current database uniqueness again. A browser-supplied HasError = false or candidate array is not trusted authorization. Database state can change after preview. Perform final validation and writes in a transaction, backed by unique constraints.

See archive validation for external-file budgets and ownership. For built-in preview sessions covering users, roles, menus and grants, use TAdmin configuration workbooks.