forked from jecovier/vue-json-excel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsonExcel.vue
323 lines (303 loc) · 8.65 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
<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,
required: false
},
// 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,
required: false
},
// 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)
title: {
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,
},
},
computed: {
// unique identifier
idName() {
var now = new Date().getTime();
return "export_" + now;
},
downloadFields() {
if (this.fields !== undefined) return this.fields;
if (this.exportFields !== undefined) 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
if (this.title != null) {
xlsData += this.parseExtraData(
this.title,
'<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.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) {
var csvData = [];
//Header
if (this.title != null) {
csvData.push(this.parseExtraData(this.title, "${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] + '\"'; // 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++) {
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/ig,"<br/>"));
else 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) {
return new Blob([data], { type: mime });
}
} // end methods
};
</script>