Last active
December 29, 2016 11:56
-
-
Save TWithers/9a1310929af0722b3e0c to your computer and use it in GitHub Desktop.
Angular Excel file with SheetJS and Papa Parse
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
(function(angular){ | |
angular | |
.module('tm-directives') | |
.directive('tmExcelImport',tmExcelImport); | |
tmExcelImport.$inject=['$timeout']; | |
function tmExcelImport($timeout){ | |
var directive = { | |
scope:{ | |
callback:'&tmExcelCallback' | |
}, | |
link:link | |
}; | |
return directive; | |
function link(scope, element, attr){ | |
var rABS = typeof FileReader !== "undefined" && typeof FileReader.prototype !== "undefined" && typeof FileReader.prototype.readAsBinaryString !== "undefined"; | |
element.children(":file").attr("accept",".csv, .xslx, .odt, .xls, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"); | |
element.on('change',':file',function(event){ | |
var input = $(this); | |
var files = event.target.files; | |
var i,f; | |
for (i = 0, f = files[i]; i != files.length; ++i) { | |
var reader = new FileReader(); | |
var name = f.name; | |
var ext = name.split(".").pop().toLowerCase(); | |
reader.onload = function(e) { | |
var data = e.target.result; | |
if(ext!=='csv'){ | |
var workbook = XLSX.read(data, {type: 'binary'}); | |
var result = []; | |
workbook.SheetNames.forEach(function(sheetName) { | |
var obj = XLSX.utils.sheet_to_csv(workbook.Sheets[sheetName],{RS:"\r\n"}); | |
if(obj.length > 0){ | |
result.push(obj); | |
} | |
}); | |
data = result[0]; | |
data = Papa.parse(data,{newline:"\r\n"}); | |
}else{ | |
data = Papa.parse(data); | |
} | |
$timeout(function(){ | |
scope.callback({data:data,event:event}); | |
}); | |
}; | |
if(rABS){ | |
reader.readAsBinaryString(f); | |
}else{ | |
reader.readAsArrayBuffer(f); | |
} | |
} | |
}); | |
} | |
} | |
})(window.angular); |
can pls tell me how to run this? does it have ui to upload file from local??
thank you
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In a nutshell, it is a directive that binds to an input button:
It allows you to select an excel or csv file and then imports the data as a CSV object. It uses SheetJS and Papa Parse to handle the parsing.