ExportData.js 34 KB

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