Exporting all data from Kendo Grid datasource

谁说胖子不能爱 提交于 2019-12-18 13:35:16

问题


I followed that tutorial about exporting Kendo Grid Data : http://www.kendoui.com/blogs/teamblog/posts/13-03-12/exporting_the_kendo_ui_grid_data_to_excel.aspx

Now I´m trying to export all data (not only the showed page) ... How can I do that?

I tried change the pagezise before get the data:

grid.dataSource.pageSize(grid.dataSource.total());

But with that my actual grid refresh with new pageSize. Is that a way to query kendo datasource without refresh the grid?

Thanks


回答1:


A better solution is to generate an Excel file from the real data, not from the dataSource.

1] In the html page, add

$('#export').click(function () {
    var title = "EmployeeData";
    var id = guid();
    var filter = $("#grid").data("kendoGrid").dataSource._filter;

    var data = {
        filter: filter,
        title: title,
        guid: id
    };

    $.ajax({
        url: '/Employee/Export',
        type: "POST",
        dataType: 'json',
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            window.location = kendo.format("{0}?title={1}&guid={2}", '/Employee/GetGeneratedExcel', title, id);
        }
    });
});


2] Add a method "Export" to the controller:

[HttpPost]
public JsonResult Export(KendoGridFilter filter, string guid)
{
    var gridRequest = new KendoGridRequest();
    if (filter != null)
    {
        gridRequest.FilterObjectWrapper = filter.Filters != null ? filter.ToFilterObjectWrapper() : null;
        gridRequest.Logic = filter.Logic;
    }

    var query = GetQueryable().AsNoTracking();
    var results = query.FilterBy<Employee, EmployeeVM>(gridRequest);

    using (var stream = new MemoryStream())
    {
        using (var excel = new ExcelPackage(stream))
        {
            excel.Workbook.Worksheets.Add("Employees");
            var ws = excel.Workbook.Worksheets[1];
            ws.Cells.LoadFromCollection(results);
            ws.Cells.AutoFitColumns();

            excel.Save();
            Session[guid] = stream.ToArray();
            return Json(new { success = true });
        }
    }
}


3] Also add the method "GetGeneratedExcel" to the controller:

[HttpGet]
public FileResult GetGeneratedExcel(string title, string guid)
{
    // Is there a spreadsheet stored in session?
    if (Session[guid] == null)
    {
        throw new Exception(string.Format("{0} not found", title));
    }

    // Get the spreadsheet from session.
    var file = Session[guid] as byte[];
    string filename = string.Format("{0}.xlsx", title);

    // Remove the spreadsheet from session.
    Session.Remove(title);

    // Return the spreadsheet.
    Response.Buffer = true;
    Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", filename));
    return File(file, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", filename);
}

Also see this project on github.

See this live example project where you can export the Employees to Excel. (Although this returns filtered data, but you can modify the code to ignore the kendo grid filter and always return all data.




回答2:


Really old question but:

To export all the pages use excel.allPages:

$("#grid").kendoGrid({
    toolbar: ["excel"],
    excel: {
        allPages: true
    },
    // ....
});

See Example




回答3:


Grid toolbar

..
.ToolBar(toolbar =>
    {
        toolbar.Template(
            @<text>
                @Html.Kendo().Button().Name("grid-export").HtmlAttributes(new { type = "button", data_url = @Url.Action("Export") }).Content("Export").Events(ev => ev.Click("exportGrid"))
            </text>);
    })
..

Endpoint export function

public FileResult Export([DataSourceRequest]DataSourceRequest request)
        {
            DemoEntities db = new DemoEntities();
            byte[] bytes = WriteExcel(db.Table.ToDataSourceResult(request).Data, new string[] { "Id", "Name" });

            return File(bytes,
                "application/vnd.ms-excel",
                "GridExcelExport.xls");
        }

a javascript function to generate grid remote export url with all specified parameters

function exportGrid() {
    var toolbar = $(this.element);
    var gridSelector = toolbar.closest(".k-grid");
    var grid = $(gridSelector).data("kendoGrid");
    var url = toolbar.data("url");

    var requestObject = (new kendo.data.transports["aspnetmvc-server"]({ prefix: "" }))
        .options.parameterMap({
            page: grid.dataSource.page(),
            sort: grid.dataSource.sort(),
            filter: grid.dataSource.filter()
        });

    url = url + "?" + $.param({
        "page": requestObject.page || '~',
        "sort": requestObject.sort || '~',
        "pageSize": grid.dataSource.pageSize(),
        "filter": requestObject.filter || '~',
    });
    window.open(url, '_blank');
}

For detailed solution see my sample project on Github

where u can export grid server side with current configuration (sorting, filtering, paging) using helper function



来源:https://stackoverflow.com/questions/21120909/exporting-all-data-from-kendo-grid-datasource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!