export-data.src.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  1. /* *
  2. *
  3. * Experimental data export module for Highcharts
  4. *
  5. * (c) 2010-2020 Torstein Honsi
  6. *
  7. * License: www.highcharts.com/license
  8. *
  9. * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
  10. *
  11. * */
  12. // @todo
  13. // - Set up systematic tests for all series types, paired with tests of the data
  14. // module importing the same data.
  15. 'use strict';
  16. import Axis from '../parts/Axis.js';
  17. import Chart from '../parts/Chart.js';
  18. import H from '../parts/Globals.js';
  19. var doc = H.doc, seriesTypes = H.seriesTypes, win = H.win;
  20. import U from '../parts/Utilities.js';
  21. var addEvent = U.addEvent, defined = U.defined, extend = U.extend, find = U.find, fireEvent = U.fireEvent, getOptions = U.getOptions, isNumber = U.isNumber, pick = U.pick, setOptions = U.setOptions;
  22. /**
  23. * Function callback to execute while data rows are processed for exporting.
  24. * This allows the modification of data rows before processed into the final
  25. * format.
  26. *
  27. * @callback Highcharts.ExportDataCallbackFunction
  28. * @extends Highcharts.EventCallbackFunction<Highcharts.Chart>
  29. *
  30. * @param {Highcharts.Chart} this
  31. * Chart context where the event occured.
  32. *
  33. * @param {Highcharts.ExportDataEventObject} event
  34. * Event object with data rows that can be modified.
  35. */
  36. /**
  37. * Contains information about the export data event.
  38. *
  39. * @interface Highcharts.ExportDataEventObject
  40. */ /**
  41. * Contains the data rows for the current export task and can be modified.
  42. * @name Highcharts.ExportDataEventObject#dataRows
  43. * @type {Array<Array<string>>}
  44. */
  45. import '../mixins/ajax.js';
  46. import '../mixins/download-url.js';
  47. var downloadURL = H.downloadURL;
  48. // Can we add this to utils? Also used in screen-reader.js
  49. /**
  50. * HTML encode some characters vulnerable for XSS.
  51. * @private
  52. * @param {string} html The input string
  53. * @return {string} The excaped string
  54. */
  55. function htmlencode(html) {
  56. return html
  57. .replace(/&/g, '&amp;')
  58. .replace(/</g, '&lt;')
  59. .replace(/>/g, '&gt;')
  60. .replace(/"/g, '&quot;')
  61. .replace(/'/g, '&#x27;')
  62. .replace(/\//g, '&#x2F;');
  63. }
  64. setOptions({
  65. /**
  66. * Callback that fires while exporting data. This allows the modification of
  67. * data rows before processed into the final format.
  68. *
  69. * @type {Highcharts.ExportDataCallbackFunction}
  70. * @context Highcharts.Chart
  71. * @requires modules/export-data
  72. * @apioption chart.events.exportData
  73. */
  74. /**
  75. * When set to `false` will prevent the series data from being included in
  76. * any form of data export.
  77. *
  78. * Since version 6.0.0 until 7.1.0 the option was existing undocumented
  79. * as `includeInCSVExport`.
  80. *
  81. * @type {boolean}
  82. * @since 7.1.0
  83. * @requires modules/export-data
  84. * @apioption plotOptions.series.includeInDataExport
  85. */
  86. /**
  87. * @optionparent exporting
  88. * @private
  89. */
  90. exporting: {
  91. /**
  92. * Caption for the data table. Same as chart title by default. Set to
  93. * `false` to disable.
  94. *
  95. * @sample highcharts/export-data/multilevel-table
  96. * Multiple table headers
  97. *
  98. * @type {boolean|string}
  99. * @since 6.0.4
  100. * @requires modules/export-data
  101. * @apioption exporting.tableCaption
  102. */
  103. /**
  104. * Options for exporting data to CSV or ExCel, or displaying the data
  105. * in a HTML table or a JavaScript structure.
  106. *
  107. * This module adds data export options to the export menu and provides
  108. * functions like `Chart.getCSV`, `Chart.getTable`, `Chart.getDataRows`
  109. * and `Chart.viewData`.
  110. *
  111. * The XLS converter is limited and only creates a HTML string that is
  112. * passed for download, which works but creates a warning before
  113. * opening. The workaround for this is to use a third party XLSX
  114. * converter, as demonstrated in the sample below.
  115. *
  116. * @sample highcharts/export-data/categorized/ Categorized data
  117. * @sample highcharts/export-data/stock-timeaxis/ Highstock time axis
  118. * @sample highcharts/export-data/xlsx/
  119. * Using a third party XLSX converter
  120. *
  121. * @since 6.0.0
  122. * @requires modules/export-data
  123. */
  124. csv: {
  125. /**
  126. * Formatter callback for the column headers. Parameters are:
  127. * - `item` - The series or axis object)
  128. * - `key` - The point key, for example y or z
  129. * - `keyLength` - The amount of value keys for this item, for
  130. * example a range series has the keys `low` and `high` so the
  131. * key length is 2.
  132. *
  133. * If [useMultiLevelHeaders](#exporting.useMultiLevelHeaders) is
  134. * true, columnHeaderFormatter by default returns an object with
  135. * columnTitle and topLevelColumnTitle for each key. Columns with
  136. * the same topLevelColumnTitle have their titles merged into a
  137. * single cell with colspan for table/Excel export.
  138. *
  139. * If `useMultiLevelHeaders` is false, or for CSV export, it returns
  140. * the series name, followed by the key if there is more than one
  141. * key.
  142. *
  143. * For the axis it returns the axis title or "Category" or
  144. * "DateTime" by default.
  145. *
  146. * Return `false` to use Highcharts' proposed header.
  147. *
  148. * @sample highcharts/export-data/multilevel-table
  149. * Multiple table headers
  150. *
  151. * @type {Function|null}
  152. */
  153. columnHeaderFormatter: null,
  154. /**
  155. * Which date format to use for exported dates on a datetime X axis.
  156. * See `Highcharts.dateFormat`.
  157. */
  158. dateFormat: '%Y-%m-%d %H:%M:%S',
  159. /**
  160. * Which decimal point to use for exported CSV. Defaults to the same
  161. * as the browser locale, typically `.` (English) or `,` (German,
  162. * French etc).
  163. *
  164. * @type {string|null}
  165. * @since 6.0.4
  166. */
  167. decimalPoint: null,
  168. /**
  169. * The item delimiter in the exported data. Use `;` for direct
  170. * exporting to Excel. Defaults to a best guess based on the browser
  171. * locale. If the locale _decimal point_ is `,`, the `itemDelimiter`
  172. * defaults to `;`, otherwise the `itemDelimiter` defaults to `,`.
  173. *
  174. * @type {string|null}
  175. */
  176. itemDelimiter: null,
  177. /**
  178. * The line delimiter in the exported data, defaults to a newline.
  179. */
  180. lineDelimiter: '\n'
  181. },
  182. /**
  183. * Show a HTML table below the chart with the chart's current data.
  184. *
  185. * @sample highcharts/export-data/showtable/
  186. * Show the table
  187. * @sample highcharts/studies/exporting-table-html
  188. * Experiment with putting the table inside the subtitle to
  189. * allow exporting it.
  190. *
  191. * @since 6.0.0
  192. * @requires modules/export-data
  193. */
  194. showTable: false,
  195. /**
  196. * Use multi level headers in data table. If [csv.columnHeaderFormatter
  197. * ](#exporting.csv.columnHeaderFormatter) is defined, it has to return
  198. * objects in order for multi level headers to work.
  199. *
  200. * @sample highcharts/export-data/multilevel-table
  201. * Multiple table headers
  202. *
  203. * @since 6.0.4
  204. * @requires modules/export-data
  205. */
  206. useMultiLevelHeaders: true,
  207. /**
  208. * If using multi level table headers, use rowspans for headers that
  209. * have only one level.
  210. *
  211. * @sample highcharts/export-data/multilevel-table
  212. * Multiple table headers
  213. *
  214. * @since 6.0.4
  215. * @requires modules/export-data
  216. */
  217. useRowspanHeaders: true
  218. },
  219. /**
  220. * @optionparent lang
  221. *
  222. * @private
  223. */
  224. lang: {
  225. /**
  226. * The text for the menu item.
  227. *
  228. * @since 6.0.0
  229. * @requires modules/export-data
  230. */
  231. downloadCSV: 'Download CSV',
  232. /**
  233. * The text for the menu item.
  234. *
  235. * @since 6.0.0
  236. * @requires modules/export-data
  237. */
  238. downloadXLS: 'Download XLS',
  239. /**
  240. * The text for exported table.
  241. *
  242. * @since 8.1.0
  243. * @requires modules/export-data
  244. */
  245. exportData: {
  246. /**
  247. * The category column title.
  248. */
  249. categoryHeader: 'Category',
  250. /**
  251. * The category column title when axis type set to "datetime".
  252. */
  253. categoryDatetimeHeader: 'DateTime'
  254. },
  255. /**
  256. * The text for the menu item.
  257. *
  258. * @since 6.0.0
  259. * @requires modules/export-data
  260. */
  261. viewData: 'View data table'
  262. }
  263. });
  264. /* eslint-disable no-invalid-this */
  265. // Add an event listener to handle the showTable option
  266. addEvent(Chart, 'render', function () {
  267. if (this.options &&
  268. this.options.exporting &&
  269. this.options.exporting.showTable &&
  270. !this.options.chart.forExport) {
  271. this.viewData();
  272. }
  273. });
  274. /* eslint-enable no-invalid-this */
  275. /**
  276. * Set up key-to-axis bindings. This is used when the Y axis is datetime or
  277. * categorized. For example in an arearange series, the low and high values
  278. * should be formatted according to the Y axis type, and in order to link them
  279. * we need this map.
  280. *
  281. * @private
  282. * @function Highcharts.Chart#setUpKeyToAxis
  283. */
  284. Chart.prototype.setUpKeyToAxis = function () {
  285. if (seriesTypes.arearange) {
  286. seriesTypes.arearange.prototype.keyToAxis = {
  287. low: 'y',
  288. high: 'y'
  289. };
  290. }
  291. if (seriesTypes.gantt) {
  292. seriesTypes.gantt.prototype.keyToAxis = {
  293. start: 'x',
  294. end: 'x'
  295. };
  296. }
  297. };
  298. /**
  299. * Export-data module required. Returns a two-dimensional array containing the
  300. * current chart data.
  301. *
  302. * @function Highcharts.Chart#getDataRows
  303. *
  304. * @param {boolean} [multiLevelHeaders]
  305. * Use multilevel headers for the rows by default. Adds an extra row with
  306. * top level headers. If a custom columnHeaderFormatter is defined, this
  307. * can override the behavior.
  308. *
  309. * @return {Array<Array<(number|string)>>}
  310. * The current chart data
  311. *
  312. * @fires Highcharts.Chart#event:exportData
  313. */
  314. Chart.prototype.getDataRows = function (multiLevelHeaders) {
  315. var hasParallelCoords = this.hasParallelCoordinates, time = this.time, csvOptions = ((this.options.exporting && this.options.exporting.csv) || {}), xAxis, xAxes = this.xAxis, rows = {}, rowArr = [], dataRows, topLevelColumnTitles = [], columnTitles = [], columnTitleObj, i, x, xTitle, langOptions = this.options.lang, exportDataOptions = langOptions.exportData, categoryHeader = exportDataOptions.categoryHeader, categoryDatetimeHeader = exportDataOptions.categoryDatetimeHeader,
  316. // Options
  317. columnHeaderFormatter = function (item, key, keyLength) {
  318. if (csvOptions.columnHeaderFormatter) {
  319. var s = csvOptions.columnHeaderFormatter(item, key, keyLength);
  320. if (s !== false) {
  321. return s;
  322. }
  323. }
  324. if (!item) {
  325. return categoryHeader;
  326. }
  327. if (item instanceof Axis) {
  328. return (item.options.title && item.options.title.text) ||
  329. (item.dateTime ? categoryDatetimeHeader : categoryHeader);
  330. }
  331. if (multiLevelHeaders) {
  332. return {
  333. columnTitle: keyLength > 1 ?
  334. key :
  335. item.name,
  336. topLevelColumnTitle: item.name
  337. };
  338. }
  339. return item.name + (keyLength > 1 ? ' (' + key + ')' : '');
  340. },
  341. // Map the categories for value axes
  342. getCategoryAndDateTimeMap = function (series, pointArrayMap, pIdx) {
  343. var categoryMap = {}, dateTimeValueAxisMap = {};
  344. pointArrayMap.forEach(function (prop) {
  345. var axisName = ((series.keyToAxis && series.keyToAxis[prop]) ||
  346. prop) + 'Axis',
  347. // Points in parallel coordinates refers to all yAxis
  348. // not only `series.yAxis`
  349. axis = isNumber(pIdx) ?
  350. series.chart[axisName][pIdx] :
  351. series[axisName];
  352. categoryMap[prop] = (axis && axis.categories) || [];
  353. dateTimeValueAxisMap[prop] = (axis && axis.dateTime);
  354. });
  355. return {
  356. categoryMap: categoryMap,
  357. dateTimeValueAxisMap: dateTimeValueAxisMap
  358. };
  359. },
  360. // Create point array depends if xAxis is category
  361. // or point.name is defined #13293
  362. getPointArray = function (series, xAxis) {
  363. var namedPoints = series.data.filter(function (d) { return d.name; });
  364. if (namedPoints.length &&
  365. xAxis &&
  366. !xAxis.categories &&
  367. !series.keyToAxis) {
  368. if (series.pointArrayMap) {
  369. var pointArrayMapCheck = series.pointArrayMap.filter(function (p) { return p === 'x'; });
  370. if (pointArrayMapCheck.length) {
  371. series.pointArrayMap.unshift('x');
  372. return series.pointArrayMap;
  373. }
  374. }
  375. return ['x', 'y'];
  376. }
  377. return series.pointArrayMap || ['y'];
  378. }, xAxisIndices = [];
  379. // Loop the series and index values
  380. i = 0;
  381. this.setUpKeyToAxis();
  382. this.series.forEach(function (series) {
  383. var keys = series.options.keys, xAxis = series.xAxis, pointArrayMap = keys || getPointArray(series, xAxis), valueCount = pointArrayMap.length, xTaken = !series.requireSorting && {}, xAxisIndex = xAxes.indexOf(xAxis), categoryAndDatetimeMap = getCategoryAndDateTimeMap(series, pointArrayMap), mockSeries, j;
  384. if (series.options.includeInDataExport !== false &&
  385. !series.options.isInternal &&
  386. series.visible !== false // #55
  387. ) {
  388. // Build a lookup for X axis index and the position of the first
  389. // series that belongs to that X axis. Includes -1 for non-axis
  390. // series types like pies.
  391. if (!find(xAxisIndices, function (index) {
  392. return index[0] === xAxisIndex;
  393. })) {
  394. xAxisIndices.push([xAxisIndex, i]);
  395. }
  396. // Compute the column headers and top level headers, usually the
  397. // same as series names
  398. j = 0;
  399. while (j < valueCount) {
  400. columnTitleObj = columnHeaderFormatter(series, pointArrayMap[j], pointArrayMap.length);
  401. columnTitles.push(columnTitleObj.columnTitle || columnTitleObj);
  402. if (multiLevelHeaders) {
  403. topLevelColumnTitles.push(columnTitleObj.topLevelColumnTitle ||
  404. columnTitleObj);
  405. }
  406. j++;
  407. }
  408. mockSeries = {
  409. chart: series.chart,
  410. autoIncrement: series.autoIncrement,
  411. options: series.options,
  412. pointArrayMap: series.pointArrayMap
  413. };
  414. // Export directly from options.data because we need the uncropped
  415. // data (#7913), and we need to support Boost (#7026).
  416. series.options.data.forEach(function eachData(options, pIdx) {
  417. var key, prop, val, name, point;
  418. // In parallel coordinates chart, each data point is connected
  419. // to a separate yAxis, conform this
  420. if (hasParallelCoords) {
  421. categoryAndDatetimeMap = getCategoryAndDateTimeMap(series, pointArrayMap, pIdx);
  422. }
  423. point = { series: mockSeries };
  424. series.pointClass.prototype.applyOptions.apply(point, [options]);
  425. key = point.x;
  426. name = series.data[pIdx] && series.data[pIdx].name;
  427. j = 0;
  428. // Pies, funnels, geo maps etc. use point name in X row
  429. if (!xAxis ||
  430. series.exportKey === 'name' ||
  431. (!hasParallelCoords && xAxis && xAxis.hasNames) && name) {
  432. key = name;
  433. }
  434. if (xTaken) {
  435. if (xTaken[key]) {
  436. key += '|' + pIdx;
  437. }
  438. xTaken[key] = true;
  439. }
  440. if (!rows[key]) {
  441. // Generate the row
  442. rows[key] = [];
  443. // Contain the X values from one or more X axes
  444. rows[key].xValues = [];
  445. }
  446. rows[key].x = point.x;
  447. rows[key].name = name;
  448. rows[key].xValues[xAxisIndex] = point.x;
  449. while (j < valueCount) {
  450. prop = pointArrayMap[j]; // y, z etc
  451. val = point[prop];
  452. rows[key][i + j] = pick(
  453. // Y axis category if present
  454. categoryAndDatetimeMap.categoryMap[prop][val],
  455. // datetime yAxis
  456. categoryAndDatetimeMap.dateTimeValueAxisMap[prop] ?
  457. time.dateFormat(csvOptions.dateFormat, val) :
  458. null,
  459. // linear/log yAxis
  460. val);
  461. j++;
  462. }
  463. });
  464. i = i + j;
  465. }
  466. });
  467. // Make a sortable array
  468. for (x in rows) {
  469. if (Object.hasOwnProperty.call(rows, x)) {
  470. rowArr.push(rows[x]);
  471. }
  472. }
  473. var xAxisIndex, column;
  474. // Add computed column headers and top level headers to final row set
  475. dataRows = multiLevelHeaders ? [topLevelColumnTitles, columnTitles] :
  476. [columnTitles];
  477. i = xAxisIndices.length;
  478. while (i--) { // Start from end to splice in
  479. xAxisIndex = xAxisIndices[i][0];
  480. column = xAxisIndices[i][1];
  481. xAxis = xAxes[xAxisIndex];
  482. // Sort it by X values
  483. rowArr.sort(function (// eslint-disable-line no-loop-func
  484. a, b) {
  485. return a.xValues[xAxisIndex] - b.xValues[xAxisIndex];
  486. });
  487. // Add header row
  488. xTitle = columnHeaderFormatter(xAxis);
  489. dataRows[0].splice(column, 0, xTitle);
  490. if (multiLevelHeaders && dataRows[1]) {
  491. // If using multi level headers, we just added top level header.
  492. // Also add for sub level
  493. dataRows[1].splice(column, 0, xTitle);
  494. }
  495. // Add the category column
  496. rowArr.forEach(function (// eslint-disable-line no-loop-func
  497. row) {
  498. var category = row.name;
  499. if (xAxis && !defined(category)) {
  500. if (xAxis.dateTime) {
  501. if (row.x instanceof Date) {
  502. row.x = row.x.getTime();
  503. }
  504. category = time.dateFormat(csvOptions.dateFormat, row.x);
  505. }
  506. else if (xAxis.categories) {
  507. category = pick(xAxis.names[row.x], xAxis.categories[row.x], row.x);
  508. }
  509. else {
  510. category = row.x;
  511. }
  512. }
  513. // Add the X/date/category
  514. row.splice(column, 0, category);
  515. });
  516. }
  517. dataRows = dataRows.concat(rowArr);
  518. fireEvent(this, 'exportData', { dataRows: dataRows });
  519. return dataRows;
  520. };
  521. /**
  522. * Export-data module required. Returns the current chart data as a CSV string.
  523. *
  524. * @function Highcharts.Chart#getCSV
  525. *
  526. * @param {boolean} [useLocalDecimalPoint]
  527. * Whether to use the local decimal point as detected from the browser.
  528. * This makes it easier to export data to Excel in the same locale as the
  529. * user is.
  530. *
  531. * @return {string}
  532. * CSV representation of the data
  533. */
  534. Chart.prototype.getCSV = function (useLocalDecimalPoint) {
  535. var csv = '', rows = this.getDataRows(), csvOptions = this.options.exporting.csv, decimalPoint = pick(csvOptions.decimalPoint, csvOptions.itemDelimiter !== ',' && useLocalDecimalPoint ?
  536. (1.1).toLocaleString()[1] :
  537. '.'),
  538. // use ';' for direct to Excel
  539. itemDelimiter = pick(csvOptions.itemDelimiter, decimalPoint === ',' ? ';' : ','),
  540. // '\n' isn't working with the js csv data extraction
  541. lineDelimiter = csvOptions.lineDelimiter;
  542. // Transform the rows to CSV
  543. rows.forEach(function (row, i) {
  544. var val = '', j = row.length;
  545. while (j--) {
  546. val = row[j];
  547. if (typeof val === 'string') {
  548. val = '"' + val + '"';
  549. }
  550. if (typeof val === 'number') {
  551. if (decimalPoint !== '.') {
  552. val = val.toString().replace('.', decimalPoint);
  553. }
  554. }
  555. row[j] = val;
  556. }
  557. // Add the values
  558. csv += row.join(itemDelimiter);
  559. // Add the line delimiter
  560. if (i < rows.length - 1) {
  561. csv += lineDelimiter;
  562. }
  563. });
  564. return csv;
  565. };
  566. /**
  567. * Export-data module required. Build a HTML table with the chart's current
  568. * data.
  569. *
  570. * @sample highcharts/export-data/viewdata/
  571. * View the data from the export menu
  572. *
  573. * @function Highcharts.Chart#getTable
  574. *
  575. * @param {boolean} [useLocalDecimalPoint]
  576. * Whether to use the local decimal point as detected from the browser.
  577. * This makes it easier to export data to Excel in the same locale as the
  578. * user is.
  579. *
  580. * @return {string}
  581. * HTML representation of the data.
  582. *
  583. * @fires Highcharts.Chart#event:afterGetTable
  584. */
  585. Chart.prototype.getTable = function (useLocalDecimalPoint) {
  586. var html = '<table id="highcharts-data-table-' + this.index + '">', options = this.options, decimalPoint = useLocalDecimalPoint ? (1.1).toLocaleString()[1] : '.', useMultiLevelHeaders = pick(options.exporting.useMultiLevelHeaders, true), rows = this.getDataRows(useMultiLevelHeaders), rowLength = 0, topHeaders = useMultiLevelHeaders ? rows.shift() : null, subHeaders = rows.shift(),
  587. // Compare two rows for equality
  588. isRowEqual = function (row1, row2) {
  589. var i = row1.length;
  590. if (row2.length === i) {
  591. while (i--) {
  592. if (row1[i] !== row2[i]) {
  593. return false;
  594. }
  595. }
  596. }
  597. else {
  598. return false;
  599. }
  600. return true;
  601. },
  602. // Get table cell HTML from value
  603. getCellHTMLFromValue = function (tag, classes, attrs, value) {
  604. var val = pick(value, ''), className = 'text' + (classes ? ' ' + classes : '');
  605. // Convert to string if number
  606. if (typeof val === 'number') {
  607. val = val.toString();
  608. if (decimalPoint === ',') {
  609. val = val.replace('.', decimalPoint);
  610. }
  611. className = 'number';
  612. }
  613. else if (!value) {
  614. className = 'empty';
  615. }
  616. return '<' + tag + (attrs ? ' ' + attrs : '') +
  617. ' class="' + className + '">' +
  618. val + '</' + tag + '>';
  619. },
  620. // Get table header markup from row data
  621. getTableHeaderHTML = function (topheaders, subheaders, rowLength) {
  622. var html = '<thead>', i = 0, len = rowLength || subheaders && subheaders.length, next, cur, curColspan = 0, rowspan;
  623. // Clean up multiple table headers. Chart.getDataRows() returns two
  624. // levels of headers when using multilevel, not merged. We need to
  625. // merge identical headers, remove redundant headers, and keep it
  626. // all marked up nicely.
  627. if (useMultiLevelHeaders &&
  628. topheaders &&
  629. subheaders &&
  630. !isRowEqual(topheaders, subheaders)) {
  631. html += '<tr>';
  632. for (; i < len; ++i) {
  633. cur = topheaders[i];
  634. next = topheaders[i + 1];
  635. if (cur === next) {
  636. ++curColspan;
  637. }
  638. else if (curColspan) {
  639. // Ended colspan
  640. // Add cur to HTML with colspan.
  641. html += getCellHTMLFromValue('th', 'highcharts-table-topheading', 'scope="col" ' +
  642. 'colspan="' + (curColspan + 1) + '"', cur);
  643. curColspan = 0;
  644. }
  645. else {
  646. // Cur is standalone. If it is same as sublevel,
  647. // remove sublevel and add just toplevel.
  648. if (cur === subheaders[i]) {
  649. if (options.exporting.useRowspanHeaders) {
  650. rowspan = 2;
  651. delete subheaders[i];
  652. }
  653. else {
  654. rowspan = 1;
  655. subheaders[i] = '';
  656. }
  657. }
  658. else {
  659. rowspan = 1;
  660. }
  661. html += getCellHTMLFromValue('th', 'highcharts-table-topheading', 'scope="col"' +
  662. (rowspan > 1 ?
  663. ' valign="top" rowspan="' + rowspan + '"' :
  664. ''), cur);
  665. }
  666. }
  667. html += '</tr>';
  668. }
  669. // Add the subheaders (the only headers if not using multilevels)
  670. if (subheaders) {
  671. html += '<tr>';
  672. for (i = 0, len = subheaders.length; i < len; ++i) {
  673. if (typeof subheaders[i] !== 'undefined') {
  674. html += getCellHTMLFromValue('th', null, 'scope="col"', subheaders[i]);
  675. }
  676. }
  677. html += '</tr>';
  678. }
  679. html += '</thead>';
  680. return html;
  681. };
  682. // Add table caption
  683. if (options.exporting.tableCaption !== false) {
  684. html += '<caption class="highcharts-table-caption">' + pick(options.exporting.tableCaption, (options.title.text ?
  685. htmlencode(options.title.text) :
  686. 'Chart')) + '</caption>';
  687. }
  688. // Find longest row
  689. for (var i = 0, len = rows.length; i < len; ++i) {
  690. if (rows[i].length > rowLength) {
  691. rowLength = rows[i].length;
  692. }
  693. }
  694. // Add header
  695. html += getTableHeaderHTML(topHeaders, subHeaders, Math.max(rowLength, subHeaders.length));
  696. // Transform the rows to HTML
  697. html += '<tbody>';
  698. rows.forEach(function (row) {
  699. html += '<tr>';
  700. for (var j = 0; j < rowLength; j++) {
  701. // Make first column a header too. Especially important for
  702. // category axes, but also might make sense for datetime? Should
  703. // await user feedback on this.
  704. html += getCellHTMLFromValue(j ? 'td' : 'th', null, j ? '' : 'scope="row"', row[j]);
  705. }
  706. html += '</tr>';
  707. });
  708. html += '</tbody></table>';
  709. var e = { html: html };
  710. fireEvent(this, 'afterGetTable', e);
  711. return e.html;
  712. };
  713. /**
  714. * Get a blob object from content, if blob is supported
  715. *
  716. * @private
  717. * @param {string} content
  718. * The content to create the blob from.
  719. * @param {string} type
  720. * The type of the content.
  721. * @return {string|undefined}
  722. * The blob object, or undefined if not supported.
  723. */
  724. function getBlobFromContent(content, type) {
  725. var nav = win.navigator, webKit = (nav.userAgent.indexOf('WebKit') > -1 &&
  726. nav.userAgent.indexOf('Chrome') < 0), domurl = win.URL || win.webkitURL || win;
  727. try {
  728. // MS specific
  729. if (nav.msSaveOrOpenBlob && win.MSBlobBuilder) {
  730. var blob = new win.MSBlobBuilder();
  731. blob.append(content);
  732. return blob.getBlob('image/svg+xml');
  733. }
  734. // Safari requires data URI since it doesn't allow navigation to blob
  735. // URLs.
  736. if (!webKit) {
  737. return domurl.createObjectURL(new win.Blob(['\uFEFF' + content], // #7084
  738. { type: type }));
  739. }
  740. }
  741. catch (e) {
  742. // Ignore
  743. }
  744. }
  745. /**
  746. * Generates a data URL of CSV for local download in the browser. This is the
  747. * default action for a click on the 'Download CSV' button.
  748. *
  749. * See {@link Highcharts.Chart#getCSV} to get the CSV data itself.
  750. *
  751. * @function Highcharts.Chart#downloadCSV
  752. *
  753. * @requires modules/exporting
  754. */
  755. Chart.prototype.downloadCSV = function () {
  756. var csv = this.getCSV(true);
  757. downloadURL(getBlobFromContent(csv, 'text/csv') ||
  758. 'data:text/csv,\uFEFF' + encodeURIComponent(csv), this.getFilename() + '.csv');
  759. };
  760. /**
  761. * Generates a data URL of an XLS document for local download in the browser.
  762. * This is the default action for a click on the 'Download XLS' button.
  763. *
  764. * See {@link Highcharts.Chart#getTable} to get the table data itself.
  765. *
  766. * @function Highcharts.Chart#downloadXLS
  767. *
  768. * @requires modules/exporting
  769. */
  770. Chart.prototype.downloadXLS = function () {
  771. var uri = 'data:application/vnd.ms-excel;base64,', template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" ' +
  772. 'xmlns:x="urn:schemas-microsoft-com:office:excel" ' +
  773. 'xmlns="http://www.w3.org/TR/REC-html40">' +
  774. '<head><!--[if gte mso 9]><xml><x:ExcelWorkbook>' +
  775. '<x:ExcelWorksheets><x:ExcelWorksheet>' +
  776. '<x:Name>Ark1</x:Name>' +
  777. '<x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions>' +
  778. '</x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook>' +
  779. '</xml><![endif]-->' +
  780. '<style>td{border:none;font-family: Calibri, sans-serif;} ' +
  781. '.number{mso-number-format:"0.00";} ' +
  782. '.text{ mso-number-format:"\@";}</style>' +
  783. '<meta name=ProgId content=Excel.Sheet>' +
  784. '<meta charset=UTF-8>' +
  785. '</head><body>' +
  786. this.getTable(true) +
  787. '</body></html>', base64 = function (s) {
  788. return win.btoa(unescape(encodeURIComponent(s))); // #50
  789. };
  790. downloadURL(getBlobFromContent(template, 'application/vnd.ms-excel') ||
  791. uri + base64(template), this.getFilename() + '.xls');
  792. };
  793. /**
  794. * Export-data module required. View the data in a table below the chart.
  795. *
  796. * @function Highcharts.Chart#viewData
  797. *
  798. * @fires Highcharts.Chart#event:afterViewData
  799. */
  800. Chart.prototype.viewData = function () {
  801. if (!this.dataTableDiv) {
  802. this.dataTableDiv = doc.createElement('div');
  803. this.dataTableDiv.className = 'highcharts-data-table';
  804. // Insert after the chart container
  805. this.renderTo.parentNode.insertBefore(this.dataTableDiv, this.renderTo.nextSibling);
  806. }
  807. this.dataTableDiv.innerHTML = this.getTable();
  808. fireEvent(this, 'afterViewData', this.dataTableDiv);
  809. };
  810. // Add "Download CSV" to the exporting menu.
  811. var exportingOptions = getOptions().exporting;
  812. if (exportingOptions) {
  813. extend(exportingOptions.menuItemDefinitions, {
  814. downloadCSV: {
  815. textKey: 'downloadCSV',
  816. onclick: function () {
  817. this.downloadCSV();
  818. }
  819. },
  820. downloadXLS: {
  821. textKey: 'downloadXLS',
  822. onclick: function () {
  823. this.downloadXLS();
  824. }
  825. },
  826. viewData: {
  827. textKey: 'viewData',
  828. onclick: function () {
  829. this.viewData();
  830. }
  831. }
  832. });
  833. if (exportingOptions.buttons) {
  834. exportingOptions.buttons.contextButton.menuItems.push('separator', 'downloadCSV', 'downloadXLS', 'viewData');
  835. }
  836. }
  837. // Series specific
  838. if (seriesTypes.map) {
  839. seriesTypes.map.prototype.exportKey = 'name';
  840. }
  841. if (seriesTypes.mapbubble) {
  842. seriesTypes.mapbubble.prototype.exportKey = 'name';
  843. }
  844. if (seriesTypes.treemap) {
  845. seriesTypes.treemap.prototype.exportKey = 'name';
  846. }