New to Telerik UI for ASP.NET MVCStart a free 30-day trial

Exporting Checked Columns Only in the Grid

Environment

ProductTelerik UI for ASP.NET MVC Grid
Progress Telerik UI for ASP.NET MVC versionCreated with the 2022.3.1109 version

Description

How can I create Excel documents by exporting the checked columns only in the Telerik UI for ASP.NET MVC Grid component?

Solution

To achieve the desired scenario:

  1. To handle the Excel export of the Grid, subscribe to the ExcelExport event.
  2. Enable the rows' persistence upon selection by using the .PersistSelection configuration method.
  3. Within the handler, obtain the fields of the columns that you are going to add by using the client-side .columns() method the Grid provides and map them to a key-value pair by using the .map() method.
  4. Push the cell headers from the previously obtained column fields.
  5. From there, get the selected Grid rows by using the built-in .selectedKeyNames() method, traverse through each of the items, and push their column values with the help of the previously obtained Grid column fields.
  6. Create a common function that will be responsible for creating the workbook document.
Index.cshtml
    <script src="https://unpkg.com/jszip/dist/jszip.min.js"></script> // To take full advantage of the Excel export   feature, download the JSZip library and include the file.

    @(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.ProductViewModel>()
        .Name("grid")
        .Columns(columns =>
        {
            columns.Select().Width(50);
            columns.Bound(p => p.ProductName);
            columns.Bound(p => p.UnitPrice).Width(100);
            columns.Bound(p => p.UnitsInStock).Width(100);
            columns.Bound(p => p.Discontinued).Width(100);
        })
        .ToolBar(t => t.Excel())
        .Excel(e => e.AllPages(true))
        .Pageable()
        .PersistSelection()
        .Sortable()
        .Events(events => events.ExcelExport("onExcelExport"))
        .DataSource(dataSource => dataSource
            .Ajax()
            .Model(model => model.Id(p => p.ProductID))
            .Read(read => read.Action("Selection_Read", "Grid"))
        )
    )

For the complete implementation of the suggested approach, refer to the Telerik REPL example on exporting checked columns only in the Grid.

More ASP.NET MVC Grid Resources

See Also