Hi vidhya16,
Export2Excel supports current page to export. So you need to generate the table from JSON data and then export the table.
Refer below sample code.
HTML
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/angular-utils-pagination@0.11.1/dirPagination.js"></script>
<script src="table2excel.js" type="text/javascript"></script>
<script type="text/javascript">
var app = angular.module('MyApp', ['angularUtils.directives.dirPagination'])
app.controller('MyController', function ($scope) {
$scope.Customers = [
{ CustomerId: 1, Name: "John Hammond", Country: "United States" },
{ CustomerId: 2, Name: "Mudassar Khan", Country: "India" },
{ CustomerId: 3, Name: "Suzanne Mathews", Country: "France" },
{ CustomerId: 4, Name: "Robert Schidner", Country: "Russia" }
];
$scope.Export = function () {
var customers = $scope.Customers;
if ($scope.Customers.length > 0) {
var table = GenerateHTMLTable(customers);
// Export the generated table to Excel.
$(table).table2excel({
filename: "Table.xls"
});
}
}
});
function GenerateHTMLTable(json) {
// Create a HTML Table element.
var table = document.createElement("TABLE");
//Get the columns name.
var col = [];
for (var key in json[0]) {
if (key !== "$$hashKey") {
col.push(key);
}
}
// Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < col.length; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = col[i];
row.appendChild(headerCell);
}
// Add the data rows.
for (var i = 0; i < json.length; i++) {
row = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = json[i][col[j]];
}
}
return table;
}
</script>
<div ng-app="MyApp" ng-controller="MyController">
<table id="tblCustomers" cellpadding="0" cellspacing="0">
<tr>
<th>Customer Id</th>
<th>Name</th>
<th>Country</th>
</tr>
<tbody>
<tr dir-paginate="m in Customers|itemsPerPage:2">
<td>{{m.CustomerId}}</td>
<td>{{m.Name}}</td>
<td>{{m.Country}}</td>
</tr>
</tbody>
</table>
<dir-pagination-controls direction-links="true" boundary-links="true">
</dir-pagination-controls><br />
<input type="button" value="Export" ng-click="Export()" />
</div>
Screenshot