javascript 从 Kendo Grid 数据源导出所有数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21120909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:07:15  来源:igfitidea点击:

Exporting all data from Kendo Grid datasource

javascriptkendo-uikendo-grid

提问by Paul

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

我跟着那个关于导出剑道网格数据的教程:http: //www.kendoui.c​​om/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:

我尝试在获取数据之前更改 pagezise:

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?

但是随着我的实际网格使用新的 pageSize 刷新。这是一种在不刷新网格的情况下查询剑道数据源的方法吗?

Thanks

谢谢

采纳答案by Stef Heyenrath

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

更好的解决方案是从真实数据生成 Excel 文件,而不是从数据源生成。

1] In the html page, add

1]在html页面中,添加

$('#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:


2]向控制器添加一个方法“导出”:

[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:


3]还将方法“GetGeneratedExcel”添加到控制器:

[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.

另请参阅github上的此项目。

See thislive 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.

请参阅实时示例项目,您可以在其中将员工导出到 Excel。(虽然这会返回过滤后的数据,但您可以修改代码以忽略剑道网格过滤器并始终返回所有数据。

回答by Jaqen H'ghar

Really old questionbut:

真的很老的问题,但是:

To export all the pages use excel.allPages:

要导出所有页面,请使用excel.allPages

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

See Example

见示例

回答by softawareblog.com

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

使用所有指定参数生成网格远程导出 url 的 javascript 函数

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

有关详细解决方案,请参阅我在Github 上的示例项目

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

您可以在其中使用辅助函数导出具有当前配置(排序、过滤、分页)的网格服务器端