Skip to content
All components SpreadsheetImport

SpreadsheetImport

On this page

A wizard that imports a CSV, TSV, text, .xlsx or .xls file, or pasted rows, in five steps: file, columns, values, review and import (KlySpreadsheetImport). It renders a SpreadsheetImporter that you create from a typed schema, and it never touches your row class: it reads and edits cells as text. The importer holds the state, and OnSubmit of the schema receives the importable rows as typed values.

Examples

A schema and a loaded file

SpreadsheetSchema.For builds the schema from the properties of the row class: the kind of each column follows the property type, and an enum column offers one option per value unless Options gives labels and aliases such as the euro sign. A property that cannot hold an empty cell, such as the decimal or the enum here, makes its column required. The file is loaded from code with LoadText, which detects the separator and the header row, and the component shows it because it subscribes to the Changed event of the importer. The second row has a negative price, so the Min rule blocks it. The wizard needs an interactive render mode to move between steps.

Import prices

prices.csv
CSV
prices.csv 3 rows · 1 sheet · Column names on row 1
Razor
<KlySpreadsheetImport Importer="_importer" Title="Import prices" />

@code {
    public enum Currency { Eur, Usd }

    public sealed class PriceRow
    {
        public string? Sku { get; set; }
        public decimal Price { get; set; }
        public Currency Currency { get; set; }
    }

    private const string Csv = "SKU;Unit price;Currency\nA-1;12,50;€\nA-2;-3;USD\nA-3;7,25;USD";

    private SpreadsheetImporter<PriceRow> _importer = default!;

    protected override void OnInitialized()
    {
        _importer = new SpreadsheetImporter<PriceRow>(SpreadsheetSchema.For<PriceRow>(s =>
        {
            s.Column(r => r.Sku, c => c.Label("SKU").Required());
            s.Column(r => r.Price, c => c.Label("Unit price").DecimalSeparator(',').Rule(SpreadsheetRule.Min(0m)));
            s.Column(r => r.Currency, c => c.Options(
            [
                new SpreadsheetOption<Currency>(Currency.Eur, "Euro", ["€"]),
                new SpreadsheetOption<Currency>(Currency.Usd, "US dollar", ["$"]),
            ]));
            s.OnSubmit = _ => Task.FromResult<IReadOnlyList<SpreadsheetRejectedRow>?>(null);
        }));
        _importer.LoadText(Csv, "prices.csv");
    }
}

The importer scans the first rows of the file and picks the one that matches the most columns, so the title above the header is ignored and HeaderRowNumber says where the header was found. Headers lists alternative spellings of a column, DecimalSeparator reads 49,90, and Pattern and Min add rules with a message. A blocked row does not reach OnSubmit, which receives the importable rows, each one with the typed row in Value. PageSize changes the rows of the review table per page. Keep the importer in a field of the page, one per user and per import.

Import products

products.csv
CSV
products.csv 4 rows · 1 sheet · Column names on row 2

Header found on line 2. Rows received by OnSubmit: none yet.

Razor
<div class="flex w-full flex-col gap-3">
    <KlySpreadsheetImport Importer="_importer" Title="Import products" PageSize="5" />
    <p class="m-0 text-sm text-(--klyroo-text-muted)">
        Header found on line @_importer.HeaderRowNumber. Rows received by OnSubmit: @(_submitted?.ToString() ?? "none yet").
    </p>
</div>

@code {
    public sealed class ProductRow
    {
        public string? Sku { get; set; }
        public string? Name { get; set; }
        public decimal Price { get; set; }
        public int? Stock { get; set; }
    }

    private const string Csv = "Supplier export;;;\nRéférence;Désignation;Prix HT;Stock\nAB-100;Keyboard;49,90;120\nab-101;Mouse;24,5;300\nAB-102;Headset;-5;12\n;No reference;12;1";

    private SpreadsheetImporter<ProductRow> _importer = default!;
    private int? _submitted;

    protected override void OnInitialized()
    {
        _importer = new SpreadsheetImporter<ProductRow>(SpreadsheetSchema.For<ProductRow>(s =>
        {
            s.Column(r => r.Sku, c => c.Label("SKU").Headers("Référence", "Reference").Required()
                .Rule(SpreadsheetRule.Pattern("^[A-Z]{2}-[0-9]{3}$", "Use the form AB-123")));
            s.Column(r => r.Name, c => c.Label("Name").Headers("Désignation", "Designation").Required());
            s.Column(r => r.Price, c => c.Label("Unit price").Headers("Prix HT").DecimalSeparator(',')
                .Rule(SpreadsheetRule.Min(0m, "The price cannot be negative")));
            s.Column(r => r.Stock, c => c.Label("Stock"));
            s.OnSubmit = rows =>
            {
                _submitted = rows.Count;
                InvokeAsync(StateHasChanged);
                return Task.FromResult<IReadOnlyList<SpreadsheetRejectedRow>?>(null);
            };
        }));
        _importer.LoadText(Csv, "products.csv");
    }
}

Pasted rows without the wizard

Paste is LoadText with the default name clipboard.tsv, and cells copied from Excel or Google Sheets arrive separated by tabs, which the separator detection recognizes. With Wizard false the component renders only the current step, with no step bar and no buttons, so your page decides when to move on, with NextStep, PreviousStep and SubmitAsync on the importer. Loading needs an interactive render mode.

Import

Or paste rows copied from a spreadsheet
Expected columns:
Email*Age*
Razor
<div class="flex w-full flex-col gap-3">
    <KlyTextarea @bind-Value="_pasted" Rows="4" Placeholder="Paste rows copied from Excel or Sheets" />
    <div><KlyButton Label="Load the rows" OnClick="Load" /></div>
    <KlySpreadsheetImport Importer="_importer" Wizard="false" />
</div>

@code {
    public sealed class Person
    {
        public string? Email { get; set; }
        public int Age { get; set; }
    }

    private SpreadsheetImporter<Person> _importer = default!;
    private string? _pasted = "Email\tAge\nada@example.com\t31\nalan@example.com\t45";

    protected override void OnInitialized() =>
        _importer = new SpreadsheetImporter<Person>(SpreadsheetSchema.For<Person>(s =>
        {
            s.Column(r => r.Email, c => c.Required().Rule(SpreadsheetRule.Email()));
            s.Column(r => r.Age, c => c.Rule(SpreadsheetRule.Between(0, 120)));
        }));

    private void Load() => _importer.Paste(_pasted ?? "");
}

API

KlySpreadsheetImport

Parameters

Name Type Default Description
Class string Classes added to the root element, merged last so they win over the theme.
Importer SpreadsheetImporter The importer that holds the import state. The component renders it and calls its methods. Users load a file by choosing or dropping it on the file step (CSV, TSV, text, .xlsx or .xls , through CancellationToken) ) or by pasting rows; your code can also call String) or SpreadsheetWorkbook) .
MaxFileSize Int64 The largest file users can choose, in bytes. Defaults to 10 MB.
MaxRows int? 10000 The most rows an import takes when MaxRows is not set, 10,000 by default. Rows past the limit are left out and the component says how many. null removes the limit. A MaxRows in the schema wins over this value.
PageSize int 50 The number of rows the review table shows per page, 50 by default. Users can change it with the page size list of the pager.
Title string The heading shown above the wizard. Defaults to the word Import in the language of the locale ( Import ). Your text is shown as it is.
Wizard bool true Shows the step bar and the Back, Continue and Import buttons. When false only the current step is rendered and your code moves between steps with the importer's step methods.

Events

Name Type Description
OnDownload EventCallback<SpreadsheetDownload> Called with the file when the user chooses to download the template or the invalid rows, instead of the browser download. Set it in .NET MAUI Blazor Hybrid, or to save the file your own way: the component then makes no JavaScript call.
OnMappingProfileChanged EventCallback<SpreadsheetMappingProfile> Called with the current SpreadsheetMappingProfile when the user changes the column mapping or answers a value question (and when your code does it through the importer), so the app can store it and give it back through SavedMapping . It is not called when a file is loaded or when a saved mapping is applied automatically.