简体   繁体   English

Kendo excel 导出 - 如何使用自定义模板导出列?

[英]Kendo excel export - how do I export columns with a custom template?

I have a kendo grid that I define declaritively.我有一个以声明方式定义的剑道网格。 I enable the excel export toolbar via data-toolbar='["excel"]'我通过data-toolbar='["excel"]'启用了 excel 导出工具data-toolbar='["excel"]'

The problem is that this only exports the fields that do not have a template defined.问题是这只会导出没有定义模板的字段。 (the first 3 in the grid below: Checkpoint, Location, Patrolled By), the other columns show up in the excel document, but the cells of those columns are all empty. (下面网格中的前 3 个:检查点、位置、巡逻者),其他列显示在 excel 文档中,但这些列的单元格都是空的。

How can I get the values to show up in the excel export?如何让值显示在 excel 导出中? I'm guessing it will require pre-processing of some sort before the excel gets exported, as the excel export function doesn't interpret my custom field html templates.我猜它需要在导出 excel 之前进行某种预处理,因为 excel 导出功能不会解释我的自定义字段 html 模板。

<div id="Checkpoints">
    <div 
        ...
        data-toolbar='["excel"]'
        data-excel='{ "fileName": "CheckpointExceptionExport.xlsx", "allPages": "true" }'
        ...
        data-columns='[
            {
                "field": "checkpoint_name", 
                "title": "Checkpoint", 
                "filterable": { "cell": { "operator": "contains"}}},
            {
                "field": "location_name", 
                "title": "Location", 
                "filterable": { "cell": { "operator": "contains"}}
            },
            {
                "field": "patrolled_by", 
                "title": "Patrolled By", 
                "filterable": { "cell": { "operator": "contains"}}
            },
            {
                "field": "geotag",
                "title": "GeoTag", 
                "template": kendo.template($("#geotagTemplate").html()) 
            },
            {
                "field": "geofence",
                "title": "GeoFence",   
                "template": kendo.template($("#geofenceTemplate").html())
            },
            {
                "field": "completed",
                "title": "Completed",
                "template": kendo.template($("#completedTemplate").html())
            },
            {
                "field": "gps",
                "title": "GPS", 
                "template": kendo.template($("#gpsTemplate").html())
            }
        ]'>
    </div>
</div>

I've came across this snippet for handling the excel export event however I don't see a way to use this event handler in the way that I've defined the grid.我遇到了这个用于处理 excel 导出事件的代码段,但是我没有看到以我定义网格的方式使用这个事件处理程序的方法。

 <script>
      $("#grid").kendoGrid({
        excelExport: function(e) {
          ...
        },

      });
    </script>

Check http://docs.telerik.com/kendo-ui/controls/data-management/grid/excel-export#limitations , which explains why this happens and shows how to proceed.检查http://docs.telerik.com/kendo-ui/controls/data-management/grid/excel-export#limitations ,它解释了为什么会发生这种情况并显示了如何进行。

The Grid does not use column templates during the Excel export—it exports only the data.网格在 Excel 导出期间不使用列模板——它仅导出数据。 The reason for this behavior is that a column template might contain arbitrary HTML which cannot be converted to Excel column values.此行为的原因是列模板可能包含无法转换为 Excel 列值的任意 HTML。 For more information on how to use a column template that does not contain HTML, refer to this column template example .有关如何使用不包含 HTML 的列模板的更多信息,请参阅此列模板示例

Update更新

In order to attach a Kendo UI event handler when using declarative widget initialization, use the data-bind HTML attribute andevent binding :为了在使用声明性小部件初始化时附加 Kendo UI 事件处理程序,请使用data-bind HTML 属性和事件绑定

<div
    data-role="grid"
    data-bind="events: { excelExport: yourExcelExportHandler }">
</div>

Check the Kendo UI Grid MVVM demo for a similar example.查看Kendo UI Grid MVVM 演示以获取类似示例。

yourExcelExportHandler should be a function defined in the viewModel, similar to onSave in the above example. yourExcelExportHandler应该是yourExcelExportHandler定义的一个函数,类似于上面例子中的onSave

The excelExport event can also be attached after widget initialization . excelExport事件也可以在小部件初始化后附加。

I found this great answer by Telerik on their website: https://docs.telerik.com/kendo-ui/knowledge-base/grid-export-arbitrary-column-templates .我在 Telerik 的网站上找到了这个很好的答案: https : //docs.telerik.com/kendo-ui/knowledge-base/grid-export-arbitrary-column-templates Their helper function exports to excel with the exact template text.他们的辅助函数使用精确的模板文本导出到 excel。

<div id="grid"></div>
    <script>
      $(document).ready(function() {
        $("#grid").kendoGrid({
          dataSource: {
            type: "odata",
            transport: {
              read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
            },
            schema: {
              model : {
                fields: {
                  OrderDate: {type: "date"}
                }
              }
            },
            pageSize: 20,
            serverPaging: true
          },
          height: 550,
          toolbar: ["excel"],
          excel: {
            allPages: true
          },
          excelExport: exportGridWithTemplatesContent,
          pageable: true,
          columns: [
            {
              field: "Freight",
              hidden: true
            },
            {
              field:"OrderID",
              filterable: false
            },
            {
              field: "OrderDate",
              title: "Order Date",
              template: "<em>#:kendo.toString(OrderDate, 'd')#</em>"
            }, {
              field: "ShipName",
              title: "Ship Name",
              template: "#:ShipName.toUpperCase()#"
            }, {
              field: "ShipCity",
              title: "Ship City",
              template: "<span style='color: green'>#:ShipCity#, #:ShipCountry#</span>"
            }
          ],
          columnMenu: true
        });
      });

      function exportGridWithTemplatesContent(e){
        var data = e.data;
        var gridColumns = e.sender.columns;
        var sheet = e.workbook.sheets[0];
        var visibleGridColumns = [];
        var columnTemplates = [];
        var dataItem;
        // Create element to generate templates in.
        var elem = document.createElement('div');

        // Get a list of visible columns
        for (var i = 0; i < gridColumns.length; i++) {
          if (!gridColumns[i].hidden) {
            visibleGridColumns.push(gridColumns[i]);
          }
        }

        // Create a collection of the column templates, together with the current column index
        for (var i = 0; i < visibleGridColumns.length; i++) {
          if (visibleGridColumns[i].template) {
            columnTemplates.push({ cellIndex: i, template: kendo.template(visibleGridColumns[i].template) });
          }
        }

        // Traverse all exported rows.
        for (var i = 1; i < sheet.rows.length; i++) {
          var row = sheet.rows[i];
          // Traverse the column templates and apply them for each row at the stored column position.

          // Get the data item corresponding to the current row.
          var dataItem = data[i - 1];
          for (var j = 0; j < columnTemplates.length; j++) {
            var columnTemplate = columnTemplates[j];
            // Generate the template content for the current cell.
            elem.innerHTML = columnTemplate.template(dataItem);
            if (row.cells[columnTemplate.cellIndex] != undefined)
              // Output the text content of the templated cell into the exported cell.
              row.cells[columnTemplate.cellIndex].value = elem.textContent || elem.innerText || "";
          }
        }
      }
    </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM