Created
June 15, 2017 16:55
-
-
Save mzmousa/7ceb14342aa4decdb6b43d9d5c14480a to your computer and use it in GitHub Desktop.
Write to an excel sheet using js-xlsx with angular
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
// bower install js-xlsx | |
// in controller | |
$scope.saveAsXlsx = function() { | |
let data = [['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4, 5]]; | |
// create an excel worksheet from an array of arrays (aoa) of survey data | |
let worksheet1 = XLSX.utils.aoa_to_sheet(data); | |
// instantiate new excel workbook | |
let workbook = XLSX.utils.book_new(); | |
XLSX.utils.book_append_sheet(workbook, worksheet1, 'Worksheet1'); | |
let excelFile = XLSX.write(workbook, { type:'binary' } ); | |
let stringToArrayBuffer = function(s) { | |
let buffer = new ArrayBuffer(s.length); | |
let bufferView = new Uint8Array(buffer); | |
for (let i=0; i!=s.length; ++i) { | |
bufferView[i] = s.charCodeAt(i) & 0xFF; | |
} | |
return buffer; | |
} | |
let blob = new Blob([stringToArrayBuffer(excelFile)], { | |
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" } | |
); | |
let url = window.URL || window.webkitURL; | |
$scope.fileUrl = url.createObjectURL(blob); | |
}; | |
// in app.js | |
.config(function ($compileProvider) { | |
$compileProvider.aHrefSanitizationWhitelist(/^\s*(|blob|):/); | |
}); | |
// in .html | |
<a class="btn btn-primary" type="button" download="workbook.xlsx" ng-click="saveAsXlsx()" ng-href=" {{ fileUrl }} ">Export to XLSX</a> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment