-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
87 lines (79 loc) · 2.55 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
/**
* Function convertObjectCsv
*
* @param {string} prefix_name
* @param {object} body
* @param {object} header
* @param {string} header
*/
function convertObjectCsv(prefix_name, body, header, separator) {
var csvFile, csvLink, fileName, csv = [];
if(prefix_name === undefined){
throw('prefix_name is undefined');
} else if (body === undefined){
throw('body is undefined');
} else if (header === undefined){
throw('header is undefined');
} else if (separator === undefined){
throw('separator is undefined');
}
//Gera o nome do arquivo final com seu prefixo
fileName = prefix_name + '_' + ( new Date() ).toISOString().slice(0,22).replace(/-/g,"") + '.csv'
makecsv();
function makecsv() {
csv = _convertDataToCsv(_formatData());
_download();
}
function _formatData() {
var keys = [],
dataObj = [];
keys = Object.keys(header);
// push header
dataObj.push(header);
// push body
body.forEach(function (val, key) {
dataObj.push(val);
});
// return data csv
return sortByKeys(dataObj, keys);
}
function _convertDataToCsv(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += separator;
line += array[i][index];
}
str += line + '\r\n';
}
return str;
}
function sortByKeys(data, keys) {
var result = [];
data.forEach(function (val, key) {
var dataObj = {};
keys.forEach(function (v) {
dataObj[v] = val[v];
});
result.push(dataObj);
});
return result;
}
function _download() {
csvFile = new Blob(["\ufeff", csv], {
type: "text/csv"
});
if (window.navigator && window.navigator.msSaveOrOpenBlob) { // for IE
window.navigator.msSaveOrOpenBlob(csvFile, fileName);
} else {
csvLink = document.createElement("a");
csvLink.download = fileName;
csvLink.href = window.URL.createObjectURL(csvFile);
csvLink.style.display = "none";
document.body.appendChild(csvLink);
csvLink.click();
}
}
}