Customizing The Export To Excel Functionality In Kendo Grid Using ASP.NET Web API

Today, I came across a scenario where I need to customize the inbuilt export to excel functionality in kendo grid while exporting the grid data, i.e where I need to get some of the column data which is hidden in grid while downloading it as excel, which can easily done using show/hide column and bind function of kendo grid.

Let we see how to implement it using ASP.NET Web API as follows,

  1. Creating an ASP.NET Web API application.
  2. Creating a Controller.
  3. Test the API
  4. Using a kendo grid with MVVM pattern
  5. Customizing the Export to Excel functionality in kendo grid using ASP.NET Web API.

Creating an Empty ASP.NET Web API Project

Create a simple empty WEB API project as in the following figure:

  
 
 

Creating a Model Class

Right click on the model folder and add a new class, in my case I named it Employee.cs:

Code in Employee.cs

  1. public class Employee  
  2.   
  3.     {   
  4.         public Employee(int EmployeeID, string FirstName, string LastName)  
  5.     {  
  6.         this.EmployeeID = EmployeeID;  
  7.         this.FirstName = FirstName;  
  8.         this.LastName = LastName;  
  9.     }  
  10.     public int EmployeeID { getset; }  
  11.     public string FirstName { getset; }  
  12.     public string LastName { getset; }  
  13. }  

Creating a Controller

Right click on the Controller folder and add a new controller, in my case I named it EmployeeDetailsController.cs:

Code in EmployeeDetailsController.cs

  1. [RoutePrefix("api/EmployeeList")]  
  2.   public class EmployeeDetailsController : ApiController  
  3.   {  
  4.       [HttpGet]  
  5.       [Route("List")]  
  6.       public HttpResponseMessage EmployeeList()  
  7.       {  
  8.           try  
  9.           {  
  10.               List<Employee> _emp = new List<Employee>();  
  11.               _emp.Add(new Employee(1, "Bobb""Ross"));  
  12.               _emp.Add(new Employee(2, "Pradeep""Raj"));  
  13.               _emp.Add(new Employee(3, "Arun""Kumar"));  
  14.               _emp.Add(new Employee(4, "Dhivakar""Krishnaswamy"));  
  15.               _emp.Add(new Employee(5, "Rajasekar""Jayaprakash"));  
  16.               return Request.CreateResponse(HttpStatusCode.OK, _emp, Configuration.Formatters.JsonFormatter);  
  17.           }  
  18.           catch (Exception ex)  
  19.           {  
  20.               return Request.CreateResponse(HttpStatusCode.OK, ex.Message, Configuration.Formatters.JsonFormatter);  
  21.   
  22.           }  
  23.   
  24.   
  25.       }  
  26.   
  27.   }  

The above controller employee action will return an employee list as a response

Test the API 

Test the API using the POSTMAN/Fiddler as in the following figure :

API End Point: /api/EmployeeList/List

Type: GET

 
 
Now the API is ready to consume. 

Using a Kendo Grid with MVVM pattern

Creating a HTML page

Create a new HTML page in the project.

Design:

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title></title>  
  5.     <meta charset="utf-8" />  
  6.     
  7.     
  8.   <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.1.412/styles/kendo.common.min.css">  
  9.   <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.1.412/styles/kendo.rtl.min.css">  
  10.   <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.1.412/styles/kendo.default.min.css">  
  11.   <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.1.412/styles/kendo.mobile.all.min.css">  
  12.   
  13.   <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>  
  14.   <script src="http://kendo.cdn.telerik.com/2016.1.412/js/angular.min.js"></script>  
  15.   <script src="http://kendo.cdn.telerik.com/2016.1.412/js/jszip.min.js"></script>  
  16.   <script src="http://kendo.cdn.telerik.com/2016.1.412/js/kendo.all.min.js"></script>  
  17.     <script src="Scripts/ViewModel/Core.js"></script>  
  18.     <script src="Scripts/ViewModel/Data.js"></script>  
  19.     <script src="Scripts/ViewModel/ViewModel.js"></script>  
  20.   
  21. </head>  
  22. <body>  
  23.   
  24.     <div class="col-lg-12">  
  25.         <div id="Main" class="main"></div>  
  26.     </div>  
  27.   
  28.     <script type="text/x-kendo-template" id="Layout-temp">  
  29.         <div class="col-lg-12">  
  30.             <div id="content"></div>  
  31.         </div>  
  32.     </script>  
  33.   
  34.     <script type="text/x-kendo-template" id="Dashboard-temp">  
  35.         <div class="row margin-t10">  
  36.             <div class="col-lg-12">  
  37.                 <div data-role="grid" id="EmployeeGrid"  
  38.                      data-sortable="true"  
  39.                      data-scrollable="true"  
  40.                         data-toolbar="['excel']"  
  41.                         data-excel='{allPages:"true"}'  
  42.                      data-resizable="true"  
  43.                      data-pageable="{refresh: true, pageSizes: [25, 50, 100, 200]}"  
  44.                       
  45.                      data-columns="[  
  46.                          { 'field''EmployeeID','width':'100px','hidden':true},  
  47.                          { 'field''FirstName','width':'100px'},  
  48.                          { 'field''LastName','width':'100px' }  
  49.                 ]"  
  50.                      data-bind="source:Gridlist,events:{dataBound: onDataBound}" />  
  51.   
  52.             </div>  
  53.         </div>  
  54.     </script>  
  55.   
  56. </body>  
  57. </html>    

Creating a JavaScript files

  1. View Model: Create a JavaScript file, in my case I named it ViewModel.Js, The View-Model is a representation of your data (the Model) which will be displayed in the View.

    ViewModel.Js
  1. (function(G, $, undefined) {    
  2.     
  3.     
  4.     $.extend(true, G, {    
  5.         KendoGrid: {    
  6.             ViewModel: {    
  7.                 DashboardModel: new kendo.observable({    
  8.                     Gridlist: G.KendoGrid.Data.GridList,                        
  9.                     onDataBound: function (e) {    
  10.                         $('#EmployeeGrid thead').each(function () {    
  11.                             kendo.bind($(this), G.KendoGrid.ViewModel.DashboardModel);    
  12.                         });    
  13.                     },    
  14.                 }),    
  15.             }    
  16.         }    
  17.     });    
  18. })(window.Gni = window.Gni || {}, jQuery);    

Data: Create a JavaScript file, in my case I named it Data.Js, This script is responsible to bound the DataSource by requesting the API.

Data.js

  1. (function (G, $, K, undefined) {    
  2.     
  3.     $.extend(true, G, {    
  4.         KendoGrid: {    
  5.             Data: {    
  6.                 GridList: new K.data.DataSource({    
  7.                     //navigatable: true,    
  8.                     batch: true,    
  9.                     pageSize: 5,    
  10.                     transport: {    
  11.                         read: {    
  12.                             url: '/api/EmployeeList/List',  
  13.                             type: 'GET',    
  14.                             dataType: 'json',    
  15.                               
  16.                         },    
  17.                         parameterMap: function (data, operation) {    
  18.                             if (operation == "read") {    
  19.                                     
  20.                                 return JSON.stringify(data);    
  21.                             }    
  22.                             return data;    
  23.                         }    
  24.                     },    
  25.                     schema: {    
  26.                           
  27.                         model: {    
  28.                             id: "EmployeeID",    
  29.                             fields: {    
  30.                                 "FirstName":{type:"string"},  
  31.                                 "LastName":{type:"string"},    
  32.                                    
  33.                             }    
  34.                         }    
  35.                        },    
  36.                         
  37.                        
  38. }),    
  39.                   
  40. }    
  41. }    
  42. });    
  43. })(window.Gni = window.Gni || {}, jQuery, kendo);       

Core: Create a JavaScript file, in my case I named it Core.Js.

This core script is used to start the rendering of the templates and calls the view model to bind the data in the UI.

  1. $(function () {  
  2.     var Layout = new kendo.Layout("Layout-temp");  
  3.     var DashboardView = new kendo.View("Dashboard-temp", { model: Gni.KendoGrid.ViewModel.DashboardModel });  
  4.     var router = new kendo.Router({  
  5.         init: function () {  
  6.             Layout.render("#Main");  
  7.             Layout.showIn("#content", DashboardView);  
  8.   
  9.         }  
  10.     });  
  11.     router.start();  
  12.   
  13. });  

Result: 

 
Export to Excel:
 

As we expect the EmployeeID column is not exported, but our goal is to get the Employee ID in Excel which is hidden from grid,it is possible by modifying the bind method of grid with the help of show and hide column method.

showColumn ( number/string/object )

This method is used to show the specified column, where It can have a parameters  like number/string/object.

hideColumn(number/string/object)

This method is used to hide the specified column, where it can have a parameters like number/string/object. 

Updated code in core.js

  1. $(function () {  
  2.     var Layout = new kendo.Layout("Layout-temp");  
  3.     var DashboardView = new kendo.View("Dashboard-temp", { model: Gni.KendoGrid.ViewModel.DashboardModel });  
  4.     var router = new kendo.Router({  
  5.         init: function () {  
  6.             Layout.render("#Main");  
  7.             Layout.showIn("#content", DashboardView);  
  8.   
  9.         }  
  10.     });  
  11.     router.start();  
  12.     var exportFlag = false;  
  13.     $("#EmployeeGrid").data("kendoGrid").bind("excelExport"function (e) {  
  14.         console.log("column")  
  15.         if (!exportFlag) {  
  16.             e.sender.showColumn(0);  
  17.   
  18.             e.preventDefault();  
  19.             exportFlag = true;  
  20.             setTimeout(function () {  
  21.                 e.sender.saveAsExcel();  
  22.             });  
  23.             window.location.reload();  
  24.   
  25.         } else {  
  26.             e.sender.hideColumn(0);  
  27.   
  28.             exportFlag = false;  
  29.   
  30.         }  
  31.     });  
  32.   
  33. });  
The above kendo grid bind methods defines that while exporting the grid data to excel just show up the first column which is EmployeeID in grid export the data to excel and hide the column in grid once the export process is completed.
 
Export to Excel:
 
 
Hurray! yes, now the grid is exported with the EmployeeID as we expected. 
 
I hope you have enjoyed this article. Your valuable feedback, question, or comments about this article are always welcomed. 
 
Read more articles on jQuery:


Similar Articles