ExportData.js 36 KB

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