forked from Helvio88/angular-xlsx-model
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxlsx-model.js
94 lines (92 loc) · 4.87 KB
/
xlsx-model.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//
// xlsx-model
// ==========
//
// Directive that reads excel file(s) from '<input type="file" [multiple]>'
// via HTML5 FileReader and assigns tabular excel data to the $scope model.
//
(function() {
'use strict';
angular
.module('xlsx-model', [])
.directive(
'xlsxModel', [
'$parse',
function($parse) {
return {
restrict: 'A',
link: function(scope, el, attrs) {
var model = $parse(attrs.xlsxModel);
var modelSetter = model.assign;
var readOpts = {
type: 'binary'
};
el.bind('change',
function() {
if (attrs.multiple) {
var master = {};
var len = el[0].files.length - 1;
angular
.forEach(
el[0].files,
function(
f) {
var reader = new FileReader();
reader.onload = function(
file) {
var wb = XLSX
.read(
file.target.result,
readOpts);
master[f.name] = {};
angular
.forEach(
wb.SheetNames,
function(
name) {
master[f.name][name.trim()] = XLSX.utils
.sheet_to_json(wb.Sheets[name]);
});
if (f === el[0].files[len]) {
modelSetter(
scope,
master);
scope
.$apply();
}
}
reader
.readAsBinaryString(f);
});
} else {
var reader = new FileReader();
reader.onload = function(
file) {
var wb = XLSX
.read(
file.target.result,
readOpts);
var data = {};
angular
.forEach(
wb.SheetNames,
function(
name) {
data[name.trim()] = XLSX.utils
.sheet_to_json(wb.Sheets[name]);
});
modelSetter(
scope,
data);
scope
.$apply();
}
reader
.readAsBinaryString(el[0].files[0]);
}
});
}
};
}
]);
})();