You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kendo Grid无法导出至Excel求助:仅导出表头无tbody数据

解决Kendo Grid从HTML表格初始化后导出Excel无数据的问题

问题原因

当直接从现有HTML表格初始化Kendo Grid时,Grid默认不会将表格tbody中的数据同步到自身的**数据源(DataSource)**中。而saveAsExcel()方法是基于Grid的数据源生成Excel文件的,这就导致了仅导出表头、无内容,甚至调用方法后无反应的情况。同时如果未引入Kendo UI的Excel导出模块,也会出现方法无响应的问题。

解决方案

方案1:初始化时绑定数据源

创建Grid时,手动从HTML表格提取数据,构建为Grid的数据源:

$("#grid").kendoGrid({
    excel: {
        fileName: "GridExport.xlsx",
        filterable: true
    },
    toolbar: ["excel"],
    columns: [
        { field: "name", title: "Name" },
        { field: "position", title: "Position" },
        { field: "office", title: "Office" }
    ],
    dataSource: {
        data: extractTableData()
    }
});

// 提取HTML表格数据的工具函数
function extractTableData() {
    var dataList = [];
    $("#grid tbody tr").each(function() {
        var $row = $(this);
        dataList.push({
            name: $row.find("td:eq(0)").text().trim(),
            position: $row.find("td:eq(1)").text().trim(),
            office: $row.find("td:eq(2)").text().trim()
        });
    });
    return dataList;
}

方案2:通过导出事件手动构建Excel内容

如果不想修改数据源,可利用excelExport事件,直接从DOM中读取表格内容构建Excel:

$("#grid").kendoGrid({
    excel: {
        fileName: "GridExport.xlsx",
        filterable: true
    },
    toolbar: ["excel"],
    excelExport: function(e) {
        // 清空默认导出的空数据行
        e.workbook.sheets[0].rows = [];
        
        // 添加表头行
        var headerRow = { cells: [] };
        $("#grid thead th").each(function() {
            headerRow.cells.push({ value: $(this).text(), bold: true });
        });
        e.workbook.sheets[0].rows.push(headerRow);
        
        // 添加tbody数据行
        $("#grid tbody tr").each(function() {
            var dataRow = { cells: [] };
            $(this).find("td").each(function() {
                dataRow.cells.push({ value: $(this).text().trim() });
            });
            e.workbook.sheets[0].rows.push(dataRow);
        });
    }
});

额外注意事项

  • 必须引入Kendo UI的Excel导出模块(kendo.excel.min.js),否则saveAsExcel()方法会无响应。
  • 本地测试时,部分浏览器会默认阻止下载弹窗,需要手动允许当前站点的下载权限。

内容的提问来源于stack exchange,提问作者Jefferson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 22:37:51