New to Telerik UI for ASP.NET Core? Download free 30-day trial

Exporting Grid Column Templates to Excel

Environment

Product Progress Telerik UI for ASP.NET Core Grid
Progress Telerik UI for ASP.NET Core version Created with the 2022.3.913 version

Description

I use the Grid's Excel Export configuration but I also need to export the content of the Column Templates. How can I achieve this in the Telerik UI for ASP.NET Core Grid?

Solution

To export the content of the Column Templates:

  1. Subscribe to the ExcelExport Event of the Grid.

  2. In the handler get the first sheet of the workbook. This allows you to modify its rows later.

  3. Access the Grid's client-side instance that is available in the event's content. Then get the column by its index.
  4. Evaluate the template.
  5. Get the dataItems set that is currently loaded in the Grid.
  6. Iterate the dataItems. Use the evaluated template as a value for the respective columns.
@{
    @(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.ProductViewModel>()
    .Name("grid")

    .Columns(columns =>
    {
        columns.Bound(p => p.ProductName).Width(300);
        columns.Bound(p => p.UnitPrice).ClientTemplate("Price per unit: #: kendo.format('{0:c}', UnitPrice) #").Width(300);
        columns.Bound(p => p.UnitsOnOrder).Width(300);
        columns.Bound(p => p.UnitsInStock).Width(300);
    })
    .ToolBar(tools => tools.Excel())
    .Pageable()
    .Sortable()
    .Scrollable()
    .Groupable()
    .Excel(excel => excel
        .FileName("Kendo UI Grid Export.xlsx")
        .Filterable(true)
        .ProxyURL(Url.Action("Excel_Export_Save", "Grid"))
    )
    .Events(e => e.ExcelExport("excelExport"))
    .Reorderable(r => r.Columns(true))
    .Resizable(r => r.Columns(true))
    .ColumnMenu()
    .DataSource(dataSource => dataSource
        .Ajax()
        .PageSize(10)
        .Read(read => read.Action("Excel_Export_Read", "Grid"))
    )
)
    function excelExport(e) {
        var sheet = e.workbook.sheets[0];
        var template = kendo.template(this.columns[1].template);
        var data = this.dataSource.view();
        for (var i = 0; i < data.length; i++) {
            sheet.rows[i + 1].cells[1].value = template(data[i]);
        }
    } 

For the complete implementation of the suggested approach, refer to this Telerik REPL Example.

To learn more about the Kendo UI templating engine, see the Kendo UI Templates Article.

More ASP.NET Core Grid Resources

See Also

In this article