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
- Configure Grid selection via the
SelectionMode
andSelectedItems
parameters. - Configure Grid Excel export or Grid CSV export via command buttons, for example in the
<GridToolBarTemplate>
. - Subscribe to the
OnBeforeExport
event in<GridExcelExport>
or<GridCsvExport>
. - In the
OnBeforeExport
handler, set theData
property of the event argument object to the GridSelectedItems
collection.
<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; }
}
}