forked from highcharts/export-csv
-
Notifications
You must be signed in to change notification settings - Fork 1
/
export-csv.js
375 lines (328 loc) · 12.7 KB
/
export-csv.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
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
/**
* A Highcharts plugin for exporting data from a rendered chart as CSV, XLS or HTML table
*
* Author: Torstein Honsi
* Licence: MIT
* Version: 1.4.2
*/
/*global Highcharts, window, document, Blob */
(function (factory) {
if (typeof module === 'object' && module.exports) {
module.exports = factory;
} else {
factory(Highcharts);
}
})(function (Highcharts) {
'use strict';
var each = Highcharts.each,
pick = Highcharts.pick,
seriesTypes = Highcharts.seriesTypes,
downloadAttrSupported = document.createElement('a').download !== undefined;
Highcharts.setOptions({
lang: {
downloadCSV: 'Download CSV',
downloadXLS: 'Download XLS',
viewData: 'View data table'
}
});
/**
* Get the data rows as a two dimensional array
*/
Highcharts.Chart.prototype.getDataRows = function () {
var options = (this.options.exporting || {}).csv || {},
xAxis = this.xAxis[0],
rows = {},
rowArr = [],
dataRows,
names = [],
i,
x,
xTitle = xAxis.options.title && xAxis.options.title.text,
// Options
dateFormat = options.dateFormat || '%Y-%m-%d %H:%M:%S',
columnHeaderFormatter = options.columnHeaderFormatter || function (series, key, keyLength) {
return series.name + (keyLength > 1 ? ' ('+ key + ')' : '');
};
// Loop the series and index values
i = 0;
each(this.series, function (series) {
var keys = series.options.keys,
pointArrayMap = keys || series.pointArrayMap || ['y'],
valueCount = pointArrayMap.length,
// requireSorting = series.requireSorting,
requireSorting = true,
categoryMap = {},
j;
// Map the categories for value axes
each(pointArrayMap, function (prop) {
categoryMap[prop] = (series[prop + 'Axis'] && series[prop + 'Axis'].categories) || [];
});
if (series.options.includeInCSVExport !== false && series.visible !== false) { // #55
j = 0;
while (j < valueCount) {
names.push(columnHeaderFormatter(series, pointArrayMap[j], pointArrayMap.length));
j = j + 1;
}
each(series.points, function (point, pIdx) {
var key = requireSorting ? point.x : pIdx,
prop,
val;
j = 0;
if (!rows[key]) {
rows[key] = [];
}
rows[key].x = point.x;
// Pies, funnels, geo maps etc. use point name in X row
if (!series.xAxis || series.exportKey === 'name') {
rows[key].name = point.name;
}
while (j < valueCount) {
prop = pointArrayMap[j]; // y, z etc
val = point[prop];
rows[key][i + j] = pick(categoryMap[prop][val], val); // Pick a Y axis category if present
j = j + 1;
}
});
i = i + j;
// Look for direction data!
if (series.options.hasOwnProperty('directionData')){
var seriesName = series.options.directionData[0].fullName;
var uom = !_.isEmpty(series.options.directionData[0].uom) ? ' (' + series.options.directionData[0].uom + ')': '';
names.push(seriesName + uom);
each(series.options.directionData, function (point, pIdx) {
var key = requireSorting ? point.x : pIdx,
prop,
val;
j = 0;
if (!rows[key]) {
rows[key] = [];
}
rows[key].x = point.x;
// Pies, funnels, geo maps etc. use point name in X row
if (!series.xAxis || series.exportKey === 'name') {
rows[key].name = point.name;
}
while (j < valueCount) {
prop = pointArrayMap[j]; // y, z etc
val = point[prop];
rows[key][i + j] = pick(categoryMap[prop][val], val); // Pick a Y axis category if present
j = j + 1;
}
});
i = i + j;
}
}
});
// Make a sortable array
for (x in rows) {
if (rows.hasOwnProperty(x)) {
rowArr.push(rows[x]);
}
}
// Sort it by X values
rowArr.sort(function (a, b) {
return a.x - b.x;
});
// Add header row
if (!xTitle) {
xTitle = xAxis.isDatetimeAxis ? 'DateTime (Local)' : 'Category';
}
dataRows = [[xTitle].concat(names)];
// Add the category column
each(rowArr, function (row) {
var category = row.name;
if (!category) {
if (xAxis.isDatetimeAxis) {
if (row.x instanceof Date) {
row.x = row.x.getTime();
}
category = Highcharts.dateFormat(dateFormat, row.x);
} else if (xAxis.categories) {
category = pick(xAxis.names[row.x], xAxis.categories[row.x], row.x);
} else {
category = row.x;
}
}
// Add the X/date/category
row.unshift(category);
dataRows.push(row);
});
return dataRows;
};
/**
* Get a CSV string
*/
Highcharts.Chart.prototype.getCSV = function (useLocalDecimalPoint) {
var csv = '',
rows = this.getDataRows(),
options = (this.options.exporting || {}).csv || {},
itemDelimiter = options.itemDelimiter || ',', // use ';' for direct import to Excel
lineDelimiter = options.lineDelimiter || '\n'; // '\n' isn't working with the js csv data extraction
// Transform the rows to CSV
each(rows, function (row, i) {
var val = '',
j = row.length,
n = useLocalDecimalPoint ? (1.1).toLocaleString()[1] : '.';
while (j--) {
val = row[j];
if (typeof val === "string") {
val = '"' + val + '"';
}
if (typeof val === 'number') {
if (n === ',') {
val = val.toString().replace(".", ",");
}
}
row[j] = val;
}
// Add the values
csv += row.join(itemDelimiter);
// Add the line delimiter
if (i < rows.length - 1) {
csv += lineDelimiter;
}
});
return csv;
};
/**
* Build a HTML table with the data
*/
Highcharts.Chart.prototype.getTable = function (useLocalDecimalPoint) {
var html = '<table>',
rows = this.getDataRows();
// Transform the rows to HTML
each(rows, function (row, i) {
var tag = i ? 'td' : 'th',
val,
j,
n = useLocalDecimalPoint ? (1.1).toLocaleString()[1] : '.';
html += '<tr>';
for (j = 0; j < row.length; j = j + 1) {
val = row[j];
// Add the cell
if (typeof val === 'number') {
val = val.toString();
if (n === ',') {
val = val.replace('.', n);
}
html += '<' + tag + ' class="number">' + val + '</' + tag + '>';
} else {
html += '<' + tag + '>' + (val === undefined ? '' : val) + '</' + tag + '>';
}
}
html += '</tr>';
});
html += '</table>';
return html;
};
function getContent(chart, href, extension, content, MIME) {
var a,
blobObject,
name,
options = (chart.options.exporting || {}).csv || {},
url = options.url || 'http://www.highcharts.com/studies/csv-export/download.php';
if (chart.options.exporting.filename) {
name = chart.options.exporting.filename;
} else if (chart.title) {
name = chart.title.textStr.replace(/ /g, '-').toLowerCase();
} else {
name = 'chart';
}
// MS specific. Check this first because of bug with Edge (#76)
if (window.Blob && window.navigator.msSaveOrOpenBlob) {
// Falls to msSaveOrOpenBlob if download attribute is not supported
blobObject = new Blob([content]);
window.navigator.msSaveOrOpenBlob(blobObject, name + '.' + extension);
// Download attribute supported
} else if (downloadAttrSupported) {
a = document.createElement('a');
a.href = href;
a.target = '_blank';
a.download = name + '.' + extension;
document.body.appendChild(a);
a.click();
a.remove();
} else {
// Fall back to server side handling
Highcharts.post(url, {
data: content,
type: MIME,
extension: extension
});
}
}
/**
* Call this on click of 'Download CSV' button
*/
Highcharts.Chart.prototype.downloadCSV = function () {
var csv = this.getCSV(true);
getContent(
this,
'data:text/csv,\uFEFF' + csv.replace(/\n/g, '%0A'),
'csv',
csv,
'text/csv'
);
};
/**
* Call this on click of 'Download XLS' button
*/
Highcharts.Chart.prototype.downloadXLS = function () {
var uri = 'data:application/vnd.ms-excel;base64,',
template = '<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><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>' +
'<x:Name>Ark1</x:Name>' +
'<x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->' +
'<style>td{border:none;font-family: Calibri, sans-serif;} .number{mso-number-format:"0.00";}</style>' +
'<meta name=ProgId content=Excel.Sheet>' +
'<meta charset=UTF-8>' +
'</head><body>' +
this.getTable(true) +
'</body></html>',
base64 = function (s) {
return window.btoa(unescape(encodeURIComponent(s))); // #50
};
getContent(
this,
uri + base64(template),
'xls',
template,
'application/vnd.ms-excel'
);
};
/**
* View the data in a table below the chart
*/
Highcharts.Chart.prototype.viewData = function () {
if (!this.insertedTable) {
var div = document.createElement('div');
div.className = 'highcharts-data-table';
// Insert after the chart container
this.renderTo.parentNode.insertBefore(div, this.renderTo.nextSibling);
div.innerHTML = this.getTable();
this.insertedTable = true;
}
};
// Add "Download CSV" to the exporting menu. Use download attribute if supported, else
// run a simple PHP script that returns a file. The source code for the PHP script can be viewed at
// https://raw.github.com/highslide-software/highcharts.com/master/studies/csv-export/csv.php
if (Highcharts.getOptions().exporting) {
Highcharts.getOptions().exporting.buttons.contextButton.menuItems.push({
textKey: 'downloadCSV',
onclick: function () { this.downloadCSV(); }
}, {
textKey: 'downloadXLS',
onclick: function () { this.downloadXLS(); }
}, {
textKey: 'viewData',
onclick: function () { this.viewData(); }
});
}
// Series specific
if (seriesTypes.map) {
seriesTypes.map.prototype.exportKey = 'name';
}
if (seriesTypes.mapbubble) {
seriesTypes.mapbubble.prototype.exportKey = 'name';
}
});