How to export HTML table content to excel file
How to export HTML table content to excel file
I want to display the table data from the HTML page in an excel sheet with the click of a button. I have tried various onclick functions and Directives but it’s not working.
vito Selected answer as best September 21, 2021
To convert HTML data into excel table you have to insert some script in index.html
<script data-require="[email protected]*" 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>
and create a function onclick that will convert data into excel table
as stated below
<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> /*table.html contain the table which we need to convert to excel sheet*/ <ng-include src="'table.html'"></ng-include> <button ng-click='tc.changeRow2()'>Modify object</button> </div> </body> <script> 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'; } }); </script>
vito Selected answer as best September 21, 2021