Skip to content

Instantly share code, notes, and snippets.

@TWithers
Last active December 29, 2016 11:56
Show Gist options
  • Save TWithers/9a1310929af0722b3e0c to your computer and use it in GitHub Desktop.
Save TWithers/9a1310929af0722b3e0c to your computer and use it in GitHub Desktop.
Angular Excel file with SheetJS and Papa Parse
(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);
@TWithers
Copy link
Author

In a nutshell, it is a directive that binds to an input button:

<style>
.btn-file {
  position: relative;
  overflow: hidden;
}
.btn-file input[type=file] {
  position: absolute;
  top: 0;
  right: 0;
  min-width: 100%;
  min-height: 100%;
  font-size: 100px;
  text-align: right;
  filter: alpha(opacity=0);
  opacity: 0;
  background: red;
  cursor: inherit;
  display: block;
}
input[readonly] {
  background-color: white !important;
  cursor: text !important;
}
</style>
<span class="btn btn-file btn-success" tm-excel-import tm-excel-callback="vm.uploadExcel(data)">
     <input type="file"/>
</span>

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.

@suriyaJaay
Copy link

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