<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Example - example-example52-production</title>
<script data-require="jquery@*" data-semver="2.1.4" src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.7/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="ExcelDirectiveExample">
<div ng-controller="TableCtrl as tc">
<download-as-excel xlname="sample.xls" sheetname="sample" template="table1.html" object="tc"></download-as-excel>
<br />
<br />
<ng-include src="'table.html'"></ng-include>
<button ng-click='tc.changeRow2()'>Modify object</button>
</div>
</body>
</html>
angular.module('ExcelDirectiveExample', [])
.directive('downloadAsExcel', function($compile, $sce, $templateRequest) {
return {
restrict: 'E',
scope: {
template: '@',
object: '='
},
replace: true,
template: '<a class="xls">Download as Excel</a>',
link: function(scope, element, attrs) {
var contentType = 'data:application/vnd.ms-excel;base64';
var htmlS = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" ><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{sheetname}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body>{table}</body></html>';
var format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) };
var blobbed = function(data) {
var blob = new Blob([format(htmlS, data)], { type: contentType });
var blobURL = window.URL.createObjectURL(blob);
if (blobURL) {
element.attr('href', blobURL);
element.attr('download', data['name']);
}
};
scope.$watch('object', function(nv, ov) {
var tUrl = $sce.getTrustedResourceUrl(scope.template);
$templateRequest(tUrl)
.then(function(tmpl) {
var t = $('<div/>').append($compile(tmpl)(scope));
setTimeout(function() {
scope.$apply();
blobbed({
sheetname: attrs.sheetname,
name: attrs.xlname,
table: t.html()
});
}, 100);
});
}, true);
}
};
})
.controller('TableCtrl', function() {
this.rows = ['Row 1', 'Row 2', 'Row 3'];
this.cols = ['Col 1', 'Col 2', 'Col 3'];
var self = this;
this.changeRow2 = function() {
self.rows[1] = 'Modified Row 2';
}
});
<table>
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in tc.rows">
<td ng-repeat="col in tc.cols">{{row}}-{{col}}</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Excel Column 1</th>
<th>Excel Column 2</th>
<th>Excel Column 3</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in object.rows">
<td ng-repeat="col in object.cols">{{ row }} - {{ col }}</td>
</tr>
</tbody>
</table>