-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxls2json.js
108 lines (90 loc) · 2.21 KB
/
xls2json.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
"use strict";
var XLS = require('xlsjs');
var _ = require('lodash');
var pinyin = require('pinyin');
module.exports = function(fileName){
var workbook = XLS.readFile(fileName, {cellNF: true});
var sheetNameList = workbook.SheetNames;
var parseResult = [];
_.forEach(sheetNameList, function(sheetName){
var sheet = workbook.Sheets[sheetName];
var data = {};
var colNameArray = [];
for(var index in sheet){
if(sheet.hasOwnProperty(index)){
if(!index.match(/^!/)){
var item = sheet[index];
var col, row;
var matchResult = index.match(/\d+$/);
if(matchResult !== null){
row = parseInt(matchResult[0], 10);
col = index.substring(0, matchResult.index);
if(data[col] === undefined){
data[col] = {
label: col,
values: []
};
}
if(row === 1){
data[col].description = item.w;
var colName = pinyin(item.w, {
style: pinyin.STYLE_NORMAL,
heteronym: false
}).join('_');
var colNameSuffix = 0;
_.forEach(colNameArray, function(c){
if(c.name === colName){
colNameSuffix = c.suffix++;
}
});
colNameArray.push({
name: colName,
suffix: colNameSuffix
});
if(colNameSuffix > 0){
colName = colName+'_'+colNameSuffix;
}
data[col].name = colName;
}
else{
if(data[col].dataType === undefined){
var t = item.t;
switch(t){
case 'n':
data[col].dataType = 'number';
break;
case 's':
data[col].dataType = 'string';
break;
case 'b':
data[col].dataType = 'boolean';
break;
case 'e':
data[col].dataType = 'error';
break;
default:
data[col].dataType = 'string';
break;
}
}
data[col].values[row-2] = item.w;
}
}
}
}
}
var parseResultItem = {
sheetName: sheetName,
data: []
};
for(var colIndex in data){
if(data.hasOwnProperty(colIndex)){
parseResultItem.data.push(data[colIndex]);
}
}
if(parseResultItem.data.length > 0){
parseResult.push(parseResultItem);
}
});
return parseResult;
};