Sunday, June 19, 2016

Export kendo grid data to pdf,xls,xlsx,doc,docx,csv,xml format

1. Export kendo grid data to PDF (Client Side)- 

The Kendo UI grid provides client Pdf export functionality which is powered by the underlying Drawing API engine of the Kendo UI framework. To enable it, include the corresponding command to the grid toolbar and configure the pdf export settings in par with your preferences. For instance, you can specify to export all pages, margins, paper size, font, etc. To initiate export programmatically, you can call the saveAsPdf method from the client API.  Furthermore, you have the ability to customize the look and feel of the exported grid table by wiring the pdfExport event of the grid.
  <script>
        $(document).ready(function () {
            $("#grid").kendoGrid({
                toolbar: ["pdf"],
                pdf: {
                    allPages: true,
                    avoidLinks: true,
                    paperSize: "A4",
                    margin: { top: "2cm", left: "1cm", right: "1cm", bottom: "1cm" },
                    landscape: true,
                    repeatHeaders: true,
                    template: $("#page-template").html(),
                    scale: 0.8
                },
                dataSource: {
                    type: "odata",
                    transport: {
                        read: "//demos.telerik.com/kendo-ui/service/Northwind.svc/Customers"
                    },
                    pageSize: 20
                },
                height: 550,
                sortable: true,
                pageable: {
                    refresh: true,
                    pageSizes: true,
                    buttonCount: 5
                },
                columns: [{
                    field: "ContactTitle",
                    title: "Contact Title",hidden:false
                }, {
                    field: "CompanyName",
                    title: "Company Name",hidden:false
                }, {
                    field: "Country",
                    width: 150,hidden:true
                }]
            });
        });
    </script>

Programmatically Export to PDF:

Toolbar option to provide an export option is great. It lets you add export feature without much of you doing any coding. But what if you have a situation where you want to a button outside of the Grid i.e. no toolbar button. And you want the grid to be exported to PDF on click of that external button. Kendo UI Grid covers you in this scenario by exposing a method called “saveAsPDF()”. You just grab instance of the grid at runtime and invoke the method “saveAsPDF()” to start the export. That’s as easy and simple it is. Here is the code snippet to show this:

<div id="grid"></div>
<br>
<button id="btnExport">Export to PDF</button>
<script>
$("#btnExport").kendoButton(
{
click:function(){
$("#grid").data("kendoGrid").saveAsPDF();
}
});
</script>

Customizing the Exported PDF File:

Kendo UI Grid also provides certain options which can be set on the grid itself and these options will control how the PDF exported file has to be shaped. Here are the options supported for PDF export:

PropertyTypeDescription
authorStringAuthor of PDF Document
creatorStringCreator of PDF Document. Defaults to “Kendo UI PDF Generator”
dateDateDate when PDF Document was created. Defaults to current date
fileNameStringName of the exported PDF Document
keywordsStringKeywords of exported PDF Document
landscapeBooleanPaper dimension setting. Default is false
marginObjectSpecify margins of the page
paperSizeStringSpecify paper size of PDF Document. e.g. A4, A3 etc
subjectStringSpecify subject of the PDF Document
titleStringSpecify title of PDF Document

Here is the code snippet on how to set the PDF options:
<script>
   $("#grid").kendoGrid({

       tooldbar:[“pdf”],

        pdf:{

              author:"Dhananjay Tathe",

              creator:"Saviant Consulting",

              date:new Date(),
              fileName:"Your File Name.pdf",
              keywords:"keywords",
              landscape:false,
              margin:{
                      left: 10,
                      right: "10pt",
              top: "10mm",
               bottom: "1in"
              },
              paperSize:"A4",
              subject:"PDF subject",
              title:"PDF title"
       },   
       
   });
</script>

2. Export kendo grid data to Excel (Client Side) - 

The Kendo UI grid provides client Excel export functionality which can be directly utilized to serve the purpose to share data in the aforementioned ways. To enable it, include the corresponding command to the grid toolbar and configure the export settings accordingly. Alternatively, you can trigger Excel export by invoking the saveAsExcel method from the client API of the grid.  Additionally, you have the option to customize the rows/columns and cells of the exported file by intercepting the excelExport event. 
<script>
        $("#grid").kendoGrid({
            toolbar: ["excel"],
            excel: {
                fileName: "Your File Name.xlsx",
                proxyURL: "//demos.telerik.com/kendo-ui/service/export",
                filterable: true
            },
            dataSource: {
                type: "odata",
                transport: {
                    read: "//demos.telerik.com/kendo-ui/service/Northwind.svc/Products"
                },
                schema:{
                    model: {
                        fields: {
                            ProductId: { type: "number" },
                            ProductName: { type: "string" },
                            UnitPrice: { type: "number" },
                            UnitsOnOrder: { type: "number" },
                            UnitsInStock: { type: "number" }
                        }
                    }
                },
                pageSize: 7,       
            sortable: true,
            pageable: true,
            groupable: true,
            filterable: true,
            columnMenu: true,
            reorderable: true,
            resizable: true,
            columns: [
                { width: 300, locked: true, field: "ProductName", title:"Product Name"},
                { width: 300, field: "UnitPrice", title: "Unit Price"},
                { width: 300, field: "UnitsOnOrder", title: "Units On Order"},
                { width: 300, field: "UnitsInStock", title: "Units In Stock"}             
            ]
        });

    </script>

Programmatically Export to Excel :


So far we have seen how the inbuilt feature of toolbar helps you to provide the excel export capability with juts a single setting. What if you have a scenario where you don’t need a toolbar button the grid rather you need a button outside the grid and on click of this external button excel file should be exported. Well even this scenario is covered by the export feature of Kendo UI Grid. Grid API exposes a single method called “saveAsExcel()” which can be invoked on the Grid at runtime and the excel file will be exported. Let’s see this in action. Here is the code snippet to do this:

<div id="grid"></div>

<button id="btnExport">Export to Excel</button>

<script>
  $("#btnExport").kendoButton({
    click: function()
    {
      $("#grid").data("kendoGrid").saveAsExcel()
    }
  })
    $("#grid").kendoGrid({
        excel: {
          fileName: "File Name.xlsx",
          filterable:true,
          allPages:false
        },
        
       });

Customizing the Exported Excel File:


PropertyTypeDescription
excelObjectConfigure the Kendo UI Grid Excel export settings
excel.fileNameStringConfigure the file name of the exported excel file
excel.filterableBooleanConfigure whether exported excel file will have column filtering or not
Excel.allPagesBooleanConfigure if all pages data need to be exported. Default is false
Let’s see the above excel options in action. Here is a code snippet which sets the excel options on the Grid:

<script>

    $("#grid").kendoGrid({

        toolbar:["excel"],
        excel:{
    filename:"filename.xslx",
    filterable:true,
    allPages:false
        },
        ….

    
    });
</script>