-
Notifications
You must be signed in to change notification settings - Fork 168
/
JsonExcel.vue
360 lines (339 loc) · 9.84 KB
/
JsonExcel.vue
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
<template>
<div :id="idName" @click="generate">
<slot> Download {{ name }} </slot>
</div>
</template>
<script>
import download from "downloadjs";
export default {
props: {
// mime type [xls, csv]
type: {
type: String,
default: "xls",
},
// Json to download
data: {
type: Array,
required: false,
default: null,
},
// fields inside the Json Object that you want to export
// if no given, all the properties in the Json are exported
fields: {
type: Object,
default: () => null,
},
// this prop is used to fix the problem with other components that use the
// variable fields, like vee-validate. exportFields works exactly like fields
exportFields: {
type: Object,
default: () => null,
},
// Use as fallback when the row has no field values
defaultValue: {
type: String,
required: false,
default: "",
},
// Title(s) for the data, could be a string or an array of strings (multiple titles)
header: {
default: null,
},
// Footer(s) for the data, could be a string or an array of strings (multiple footers)
footer: {
default: null,
},
// filename to export
name: {
type: String,
default: "data.xls",
},
fetch: {
type: Function,
},
meta: {
type: Array,
default: () => [],
},
worksheet: {
type: String,
default: "Sheet1",
},
//event before generate was called
beforeGenerate: {
type: Function,
},
//event before download pops up
beforeFinish: {
type: Function,
},
// Determine if CSV Data should be escaped
escapeCsv: {
type: Boolean,
default: true,
},
// long number stringify
stringifyLongNum: {
type: Boolean,
default: false,
},
},
computed: {
// unique identifier
idName() {
var now = new Date().getTime();
return "export_" + now;
},
downloadFields() {
if (this.fields) return this.fields;
if (this.exportFields) return this.exportFields;
},
},
methods: {
async generate() {
if (typeof this.beforeGenerate === "function") {
await this.beforeGenerate();
}
let data = this.data;
if (typeof this.fetch === "function" || !data) data = await this.fetch();
if (!data || !data.length) {
return;
}
let json = this.getProcessedJson(data, this.downloadFields);
if (this.type === "html") {
// this is mainly for testing
return this.export(
this.jsonToXLS(json),
this.name.replace(".xls", ".html"),
"text/html"
);
} else if (this.type === "csv") {
return this.export(
this.jsonToCSV(json),
this.name.replace(".xls", ".csv"),
"application/csv"
);
}
return this.export(
this.jsonToXLS(json),
this.name,
"application/vnd.ms-excel"
);
},
/*
Use downloadjs to generate the download link
*/
export: async function (data, filename, mime) {
let blob = this.base64ToBlob(data, mime);
if (typeof this.beforeFinish === "function") await this.beforeFinish();
download(blob, filename, mime);
},
/*
jsonToXLS
---------------
Transform json data into an xml document with MS Excel format, sadly
it shows a prompt when it opens, that is a default behavior for
Microsoft office and cannot be avoided. It's recommended to use CSV format instead.
*/
jsonToXLS(data) {
let xlsTemp =
'<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta name=ProgId content=Excel.Sheet> <meta name=Generator content="Microsoft Excel 11"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>${worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><style>br {mso-data-placement: same-cell;}</style></head><body><table>${table}</table></body></html>';
let xlsData = "<thead>";
const colspan = Object.keys(data[0]).length;
let _self = this;
//Header
const header = this.header || this.$attrs.title;
if (header) {
xlsData += this.parseExtraData(
header,
'<tr><th colspan="' + colspan + '">${data}</th></tr>'
);
}
//Fields
xlsData += "<tr>";
for (let key in data[0]) {
xlsData += "<th>" + key + "</th>";
}
xlsData += "</tr>";
xlsData += "</thead>";
//Data
xlsData += "<tbody>";
data.map(function (item, index) {
xlsData += "<tr>";
for (let key in item) {
xlsData +=
"<td>" +
_self.preprocessLongNum(
_self.valueReformattedForMultilines(item[key])
) +
"</td>";
}
xlsData += "</tr>";
});
xlsData += "</tbody>";
//Footer
if (this.footer != null) {
xlsData += "<tfoot>";
xlsData += this.parseExtraData(
this.footer,
'<tr><td colspan="' + colspan + '">${data}</td></tr>'
);
xlsData += "</tfoot>";
}
return xlsTemp
.replace("${table}", xlsData)
.replace("${worksheet}", this.worksheet);
},
/*
jsonToCSV
---------------
Transform json data into an CSV file.
*/
jsonToCSV(data) {
let _self = this;
var csvData = [];
//Header
const header = this.header || this.$attrs.title;
if (header) {
csvData.push(this.parseExtraData(header, "${data}\r\n"));
}
//Fields
for (let key in data[0]) {
csvData.push(key);
csvData.push(",");
}
csvData.pop();
csvData.push("\r\n");
//Data
data.map(function (item) {
for (let key in item) {
let escapedCSV = item[key] + "";
// Escaped CSV data to string to avoid problems with numbers or other types of values
// this is controlled by the prop escapeCsv
if (_self.escapeCsv) {
escapedCSV = '="' + escapedCSV + '"'; // cast Numbers to string
if (escapedCSV.match(/[,"\n]/)) {
escapedCSV = '"' + escapedCSV.replace(/\"/g, '""') + '"';
}
}
csvData.push(escapedCSV);
csvData.push(",");
}
csvData.pop();
csvData.push("\r\n");
});
//Footer
if (this.footer != null) {
csvData.push(this.parseExtraData(this.footer, "${data}\r\n"));
}
return csvData.join("");
},
/*
getProcessedJson
---------------
Get only the data to export, if no fields are set return all the data
*/
getProcessedJson(data, header) {
let keys = this.getKeys(data, header);
let newData = [];
let _self = this;
data.map(function (item, index) {
let newItem = {};
for (let label in keys) {
let property = keys[label];
newItem[label] = _self.getValue(property, item);
}
newData.push(newItem);
});
return newData;
},
getKeys(data, header) {
if (header) {
return header;
}
let keys = {};
for (let key in data[0]) {
keys[key] = key;
}
return keys;
},
/*
parseExtraData
---------------
Parse title and footer attribute to the csv format
*/
parseExtraData(extraData, format) {
let parseData = "";
if (Array.isArray(extraData)) {
for (var i = 0; i < extraData.length; i++) {
if (extraData[i])
parseData += format.replace("${data}", extraData[i]);
}
} else {
parseData += format.replace("${data}", extraData);
}
return parseData;
},
getValue(key, item) {
const field = typeof key !== "object" ? key : key.field;
let indexes = typeof field !== "string" ? [] : field.split(".");
let value = this.defaultValue;
if (!field) value = item;
else if (indexes.length > 1)
value = this.getValueFromNestedItem(item, indexes);
else value = this.parseValue(item[field]);
if (key.hasOwnProperty("callback"))
value = this.getValueFromCallback(value, key.callback);
return value;
},
/*
convert values with newline \n characters into <br/>
*/
valueReformattedForMultilines(value) {
if (typeof value == "string") return value.replace(/\n/gi, "<br/>");
else return value;
},
preprocessLongNum(value) {
if (this.stringifyLongNum) {
if (String(value).startsWith("0x")) {
return value;
}
if (!isNaN(value) && value != "") {
if (value > 99999999999 || value < 0.0000000000001) {
return '="' + value + '"';
}
}
}
return value;
},
getValueFromNestedItem(item, indexes) {
let nestedItem = item;
for (let index of indexes) {
if (nestedItem) nestedItem = nestedItem[index];
}
return this.parseValue(nestedItem);
},
getValueFromCallback(item, callback) {
if (typeof callback !== "function") return this.defaultValue;
const value = callback(item);
return this.parseValue(value);
},
parseValue(value) {
return value || value === 0 || typeof value === "boolean"
? value
: this.defaultValue;
},
base64ToBlob(data, mime) {
let base64 = window.btoa(window.unescape(encodeURIComponent(data)));
let bstr = atob(base64);
let n = bstr.length;
let u8arr = new Uint8ClampedArray(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
},
}, // end methods
};
</script>