/
index.js
132 lines (104 loc) · 3.09 KB
/
index.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
var xlsx = require('node-xlsx');
var convert2NestedObj = require('./lib/2DArrayToNestedObj')
Array.prototype.first = function () {
return this[0];
}
String.prototype.toCamelCase = function() {
return this.split('.').map( s => s.replace(/^([A-Z])|[\s-_]+(\w)/g, function(match, p1, p2, offset) {
if (p2) return p2.toUpperCase();
return p1.toLowerCase();
})).join('.')
};
class failedToTransformError extends Error
{
constructor(name, message, stack)
{
super();
this.name = name
this.message = message;
this.stack = stack
}
}
function toJSON(headers, entry) {
let obj={};
headers.forEach( (e,i)=>{
obj[e] = typeof(entry[i])==='undefined' ? '' : entry[i]
})
return obj;
}
function parse( sheet, trans, isToCamelCase, sheetnum){
let xlsdata;
let xlsObjs = [];
let headers = sheet.data.first();
if( typeof headers === 'undefined'){
return;
}
headers.forEach( (e,i,arr)=>{
arr[i] = isToCamelCase ? e.trim().toCamelCase() : e.trim().replace(/\s\s+/g, ' ').split(' ').join('_');
})
let headerLength = headers.length;
if(headerLength <1){
throw new Error("No data")
}
//remove header
sheet.data.shift();
sheet.data.forEach(function (element, idx) {
if (element === headers ) {
return;
}
xlsdata = toJSON(headers, element);
if(typeof trans !== 'undefined' && trans.length > 0){
try{
trans(xlsdata);
}catch(err)
{
throw new failedToTransformError('failedToTransformError',
JSON.stringify({
'sheet number': sheetnum,
'element': JSON.stringify(xlsdata),
'index': idx,
'errorMessage': err.message
}),
err.stack)
}
}
xlsObjs.push(xlsdata);
})
return xlsObjs;
}
class XlsParser
{
constructor(trans)
{
this.transforms = typeof trans !== 'undefined' ? trans: []
}
setTranseform( func){
this.transforms = func;
}
parseXls2Json (path, option, xlsxParseOption) {
let obj = xlsx.parse(path, xlsxParseOption); // parses a file
let xlsDoc = []
obj.forEach( (e,i) => {
//sheet
let isToCamelCase = false;
if(option && typeof option.isToCamelCase !== 'undefined')
isToCamelCase = option.isToCamelCase
let o = parse(e, this.transforms ? this.transforms[i]: [], isToCamelCase, i);
if(typeof o !=='undefined'){
if(option && option.isNested){
xlsDoc.push(convert2NestedObj(o));
}else{
xlsDoc.push(o);
}
}
})
return xlsDoc;
}
}
var _ = new XlsParser();
module.exports = {
failedToTransformError,
XlsParser,
parseXls2Json: _.parseXls2Json,
setTranseform: _.setTranseform
}