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

Export to Excel Only the Filtered Rows from Grid for ASP.NET Core

Environment

Product Grid for Progress® Telerik® UI for ASP.NET Core

Description

I want to send the Grid's filtered rows to Excel.

Solution

To export only the filtered rows from the Grid for ASP.NET Core to excel with server export, follow these steps:

  1. Add the custom serialization function of the data source and serialize the filter from the client-side:
   var escapeQuoteRegExp = /'/ig;

    function encodeFilterValue(value, encode) {
        if (typeof value === "string") {
            if (value.indexOf('Date(') > -1) {
                value = new Date(parseInt(value.replace(/^\/Date\((.*?)\)\/$/, '$1'), 10));
            } else {
                value = value.replace(escapeQuoteRegExp, "''");

                if (encode) {
                    value = encodeURIComponent(value);
                }

                return "'" + value + "'";
            }
        }

        if (value && value.getTime) {
            return "datetime'" + kendo.format("{0:yyyy-MM-ddTHH-mm-ss}", value) + "'";
        }
        return value;
    }

    function serializeFilter(filter, encode) {
        if (filter.filters) {
            return $.map(filter.filters, function (f) {
                var hasChildren = f.filters && f.filters.length > 1,
                    result = serializeFilter(f, encode);

                if (result && hasChildren) {
                    result = "(" + result + ")";
                }

                return result;
            }).join("~" + filter.logic + "~");
        }

        if (filter.field) {
            return filter.field + "~" + filter.operator + "~" + encodeFilterValue(filter.value, encode);
        } else {
            return undefined;
        }
    }
    $("#export-filter").val(encodeURIComponent(serializeFilter(grid.dataSource.filter())));
  1. On the server, parse the filter into a FilterDescriptor:
var filters = FilterDescriptorFactory.Create(filter);
  1. Execute the filter expression over your data collection and retrieve the data items only:
var filteredData = students.ToDataSourceResult(new DataSourceRequest() { Filters=filters, Page=1 }).Data;

Notes

  • The filter parameter contains the currently applied filters to the columns.
  • If you encounter issues with exporting to CSV, ensure that the mime type is set correctly.

More ASP.NET Core Grid Resources

See Also

In this article