Skip to content

Instantly share code, notes, and snippets.

@mzmousa
Created June 15, 2017 16:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mzmousa/7ceb14342aa4decdb6b43d9d5c14480a to your computer and use it in GitHub Desktop.
Save mzmousa/7ceb14342aa4decdb6b43d9d5c14480a to your computer and use it in GitHub Desktop.
Write to an excel sheet using js-xlsx with angular
'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