-
Notifications
You must be signed in to change notification settings - Fork 17
/
angular-js-xlsx.js
74 lines (65 loc) · 2.26 KB
/
angular-js-xlsx.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
'use strict';
angular.module('angular-js-xlsx', [])
.directive('jsXls', function () {
return {
restrict: 'E',
template: '<input type="file" />',
replace: true,
link: function (scope, element, attrs) {
function handleSelect() {
var files = this.files;
for (var i = 0, f = files[i]; i != files.length; ++i) {
var reader = new FileReader();
var name = f.name;
reader.onload = function (e) {
if (!e) {
var data = reader.content;
} else {
var data = e.target.result;
}
/* if binary string, read with type 'binary' */
try {
var workbook = XLS.read(data, { type: 'binary' });
if (attrs.onread) {
var handleRead = scope[attrs.onread];
if (typeof handleRead === "function") {
handleRead(workbook);
}
}
} catch (e) {
if (attrs.onerror) {
var handleError = scope[attrs.onerror];
if (typeof handleError === "function") {
handleError(e);
}
}
}
// Clear input file
element.val('');
};
//extend FileReader
if (!FileReader.prototype.readAsBinaryString) {
FileReader.prototype.readAsBinaryString = function (fileData) {
var binary = "";
var pt = this;
var reader = new FileReader();
reader.onload = function (e) {
var bytes = new Uint8Array(reader.result);
var length = bytes.byteLength;
for (var i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i]);
}
//pt.result - readonly so assign binary
pt.content = binary;
$(pt).trigger('onload');
}
reader.readAsArrayBuffer(fileData);
}
}
reader.readAsBinaryString(f);
}
}
element.on('change', handleSelect);
}
};
});