Skip to content

Instantly share code, notes, and snippets.

@sp90
Created July 13, 2018 07:24
Show Gist options
  • Save sp90/bba354ba63851cdce7863b5c2cb41744 to your computer and use it in GitHub Desktop.
Save sp90/bba354ba63851cdce7863b5c2cb41744 to your computer and use it in GitHub Desktop.
A angular based file to generate excel from html
(function() {
'use strict';
angular
.module('factory.Excel', [])
.factory('Excel', Excel);
function Excel($document, $window) {
return {
create: create
};
function create(tableId, fileName, worksheetName) {
fileName = fileName && fileName + '.xls';
var uri = 'data:application/vnd.ms-excel;base64,';
var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>';
var base64 = function(s) {
return $window.btoa(unescape(encodeURIComponent(s)));
};
var format = function(s, c) {
return s.replace(/{(\w+)}/g, function(m, p) {
return c[p];
})
};
var table = angular.element(document.querySelector(tableId));
var ctx = {
worksheet: worksheetName,
table: table.html()
};
var href = uri + base64(format(template, ctx));
var browser = window.navigator.appVersion;
if ((browser.indexOf('Trident') !== -1 && browser.indexOf('rv:11') !== -1) || (browser.indexOf('MSIE 10') !== -1)) {
var builder = new window.MSBlobBuilder();
builder.append(href);
var blob = builder.getBlob('data:application/vnd.ms-excel');
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
var link = $document[0].createElement('a');
link.download = fileName;
link.href = href;
link.click();
}
return href;
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment