New to Telerik UI for Blazor? Download free 30-day trial

Export Selected Grid Rows

Environment

Product Grid for Blazor

Description

How to export to Excel only the selected rows in a Blazor Grid?

How to export only the Grid rows that the user selected?

How to export the selected items from the Grid?

How to export custom Grid data (for example the Grid selection) to CSV?

Solution

  1. Configure Grid selection via the SelectionMode and SelectedItems parameters.
  2. Configure Grid Excel export or Grid CSV export via command buttons, for example in the <GridToolBarTemplate>.
  3. Subscribe to the OnBeforeExport event in <GridExcelExport> or <GridCsvExport>.
  4. In the OnBeforeExport handler, set the Data property of the event argument object to the Grid SelectedItems collection.

Export only the selected Grid rows to Excel or CSV

<TelerikGrid Data="@GridData"
             SelectionMode="@GridSelectionMode.Multiple"
             @bind-SelectedItems="@GridSelectedItems">
    <GridToolBarTemplate>
        <GridCommandButton Command="ExcelExport"
                           Icon="@SvgIcon.FileExcel">Export Selection to Excel</GridCommandButton>
        <GridCommandButton Command="CsvExport"
                           Icon="@SvgIcon.FileCsv">Export Selection to CSV</GridCommandButton>
    </GridToolBarTemplate>
    <GridSettings>
        <GridExcelExport OnBeforeExport="@OnBeforeGridExcelExport" FileName="grid-selection" />
        <GridCsvExport OnBeforeExport="@OnBeforeGridCsvExport" FileName="grid-selection" />
    </GridSettings>
    <GridColumns>
        <GridCheckboxColumn SelectAll="true" />
        <GridColumn Field="@nameof(GridItem.Id)" />
        <GridColumn Field="@nameof(GridItem.Text)" />
    </GridColumns>
</TelerikGrid>

@code {
    private List<GridItem> GridData { get; set; }

    private IEnumerable<GridItem> GridSelectedItems { get; set; } = new List<GridItem>();

    private void OnBeforeGridExcelExport(GridBeforeExcelExportEventArgs args)
    {
        if (GridSelectedItems.Count() > 0)
        {
            args.Data = GridSelectedItems;
        }
        else
        {
            args.IsCancelled = true;
        }
    }

    private void OnBeforeGridCsvExport(GridBeforeCsvExportEventArgs args)
    {
        if (GridSelectedItems.Count() > 0)
        {
            args.Data = GridSelectedItems;
        }
        else
        {
            args.IsCancelled = true;
        }
    }

    protected override void OnInitialized()
    {
        GridData = new List<GridItem>();

        for (int i = 1; i <= 7; i++)
        {
            GridData.Add(new GridItem()
            {
                Id = i,
                Text = $"Row {i}"
            });
        }
    }

    public class GridItem
    {
        public int Id { get; set; }
        public string Text { get; set; }
    }
}

See Also

In this article