Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

buttons.flash.js 57KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468
  1. /*!
  2. * Flash export buttons for Buttons and DataTables.
  3. * 2015-2017 SpryMedia Ltd - datatables.net/license
  4. *
  5. * ZeroClipbaord - MIT license
  6. * Copyright (c) 2012 Joseph Huckaby
  7. */
  8. (function (factory) {
  9. if (typeof define === 'function' && define.amd) {
  10. // AMD
  11. define(['jquery', 'datatables.net', 'datatables.net-buttons'], function ($) {
  12. return factory($, window, document);
  13. });
  14. } else if (typeof exports === 'object') {
  15. // CommonJS
  16. module.exports = function (root, $) {
  17. if (!root) {
  18. root = window;
  19. }
  20. if (!$ || !$.fn.dataTable) {
  21. $ = require('datatables.net')(root, $).$;
  22. }
  23. if (!$.fn.dataTable.Buttons) {
  24. require('datatables.net-buttons')(root, $);
  25. }
  26. return factory($, root, root.document);
  27. };
  28. } else {
  29. // Browser
  30. factory(jQuery, window, document);
  31. }
  32. }(function ($, window, document, undefined) {
  33. 'use strict';
  34. var DataTable = $.fn.dataTable;
  35. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  36. * ZeroClipboard dependency
  37. */
  38. /*
  39. * ZeroClipboard 1.0.4 with modifications
  40. * Author: Joseph Huckaby
  41. * License: MIT
  42. *
  43. * Copyright (c) 2012 Joseph Huckaby
  44. */
  45. var ZeroClipboard_TableTools = {
  46. version: "1.0.4-TableTools2",
  47. clients: {}, // registered upload clients on page, indexed by id
  48. moviePath: '', // URL to movie
  49. nextId: 1, // ID of next movie
  50. $: function (thingy) {
  51. // simple DOM lookup utility function
  52. if (typeof (thingy) == 'string') {
  53. thingy = document.getElementById(thingy);
  54. }
  55. if (!thingy.addClass) {
  56. // extend element with a few useful methods
  57. thingy.hide = function () {
  58. this.style.display = 'none';
  59. };
  60. thingy.show = function () {
  61. this.style.display = '';
  62. };
  63. thingy.addClass = function (name) {
  64. this.removeClass(name);
  65. this.className += ' ' + name;
  66. };
  67. thingy.removeClass = function (name) {
  68. this.className = this.className.replace(new RegExp("\\s*" + name + "\\s*"), " ").replace(/^\s+/, '').replace(/\s+$/, '');
  69. };
  70. thingy.hasClass = function (name) {
  71. return !!this.className.match(new RegExp("\\s*" + name + "\\s*"));
  72. };
  73. }
  74. return thingy;
  75. },
  76. setMoviePath: function (path) {
  77. // set path to ZeroClipboard.swf
  78. this.moviePath = path;
  79. },
  80. dispatch: function (id, eventName, args) {
  81. // receive event from flash movie, send to client
  82. var client = this.clients[id];
  83. if (client) {
  84. client.receiveEvent(eventName, args);
  85. }
  86. },
  87. log: function (str) {
  88. console.log('Flash: ' + str);
  89. },
  90. register: function (id, client) {
  91. // register new client to receive events
  92. this.clients[id] = client;
  93. },
  94. getDOMObjectPosition: function (obj) {
  95. // get absolute coordinates for dom element
  96. var info = {
  97. left: 0,
  98. top: 0,
  99. width: obj.width ? obj.width : obj.offsetWidth,
  100. height: obj.height ? obj.height : obj.offsetHeight
  101. };
  102. if (obj.style.width !== "") {
  103. info.width = obj.style.width.replace("px", "");
  104. }
  105. if (obj.style.height !== "") {
  106. info.height = obj.style.height.replace("px", "");
  107. }
  108. while (obj) {
  109. info.left += obj.offsetLeft;
  110. info.top += obj.offsetTop;
  111. obj = obj.offsetParent;
  112. }
  113. return info;
  114. },
  115. Client: function (elem) {
  116. // constructor for new simple upload client
  117. this.handlers = {};
  118. // unique ID
  119. this.id = ZeroClipboard_TableTools.nextId++;
  120. this.movieId = 'ZeroClipboard_TableToolsMovie_' + this.id;
  121. // register client with singleton to receive flash events
  122. ZeroClipboard_TableTools.register(this.id, this);
  123. // create movie
  124. if (elem) {
  125. this.glue(elem);
  126. }
  127. }
  128. };
  129. ZeroClipboard_TableTools.Client.prototype = {
  130. id: 0, // unique ID for us
  131. ready: false, // whether movie is ready to receive events or not
  132. movie: null, // reference to movie object
  133. clipText: '', // text to copy to clipboard
  134. fileName: '', // default file save name
  135. action: 'copy', // action to perform
  136. handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor
  137. cssEffects: true, // enable CSS mouse effects on dom container
  138. handlers: null, // user event handlers
  139. sized: false,
  140. sheetName: '', // default sheet name for excel export
  141. glue: function (elem, title) {
  142. // glue to DOM element
  143. // elem can be ID or actual DOM element object
  144. this.domElement = ZeroClipboard_TableTools.$(elem);
  145. // float just above object, or zIndex 99 if dom element isn't set
  146. var zIndex = 99;
  147. if (this.domElement.style.zIndex) {
  148. zIndex = parseInt(this.domElement.style.zIndex, 10) + 1;
  149. }
  150. // find X/Y position of domElement
  151. var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement);
  152. // create floating DIV above element
  153. this.div = document.createElement('div');
  154. var style = this.div.style;
  155. style.position = 'absolute';
  156. style.left = '0px';
  157. style.top = '0px';
  158. style.width = (box.width) + 'px';
  159. style.height = box.height + 'px';
  160. style.zIndex = zIndex;
  161. if (typeof title != "undefined" && title !== "") {
  162. this.div.title = title;
  163. }
  164. if (box.width !== 0 && box.height !== 0) {
  165. this.sized = true;
  166. }
  167. // style.backgroundColor = '#f00'; // debug
  168. if (this.domElement) {
  169. this.domElement.appendChild(this.div);
  170. this.div.innerHTML = this.getHTML(box.width, box.height).replace(/&/g, '&');
  171. }
  172. },
  173. positionElement: function () {
  174. var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement);
  175. var style = this.div.style;
  176. style.position = 'absolute';
  177. //style.left = (this.domElement.offsetLeft)+'px';
  178. //style.top = this.domElement.offsetTop+'px';
  179. style.width = box.width + 'px';
  180. style.height = box.height + 'px';
  181. if (box.width !== 0 && box.height !== 0) {
  182. this.sized = true;
  183. } else {
  184. return;
  185. }
  186. var flash = this.div.childNodes[0];
  187. flash.width = box.width;
  188. flash.height = box.height;
  189. },
  190. getHTML: function (width, height) {
  191. // return HTML for movie
  192. var html = '';
  193. var flashvars = 'id=' + this.id +
  194. '&width=' + width +
  195. '&height=' + height;
  196. if (navigator.userAgent.match(/MSIE/)) {
  197. // IE gets an OBJECT tag
  198. var protocol = location.href.match(/^https/i) ? 'https://' : 'http://';
  199. html += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="' + protocol + 'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="' + width + '" height="' + height + '" id="' + this.movieId + '" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="' + ZeroClipboard_TableTools.moviePath + '" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="' + flashvars + '"/><param name="wmode" value="transparent"/></object>';
  200. } else {
  201. // all other browsers get an EMBED tag
  202. html += '<embed id="' + this.movieId + '" src="' + ZeroClipboard_TableTools.moviePath + '" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="' + width + '" height="' + height + '" name="' + this.movieId + '" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="' + flashvars + '" wmode="transparent" />';
  203. }
  204. return html;
  205. },
  206. hide: function () {
  207. // temporarily hide floater offscreen
  208. if (this.div) {
  209. this.div.style.left = '-2000px';
  210. }
  211. },
  212. show: function () {
  213. // show ourselves after a call to hide()
  214. this.reposition();
  215. },
  216. destroy: function () {
  217. // destroy control and floater
  218. var that = this;
  219. if (this.domElement && this.div) {
  220. $(this.div).remove();
  221. this.domElement = null;
  222. this.div = null;
  223. $.each(ZeroClipboard_TableTools.clients, function (id, client) {
  224. if (client === that) {
  225. delete ZeroClipboard_TableTools.clients[id];
  226. }
  227. });
  228. }
  229. },
  230. reposition: function (elem) {
  231. // reposition our floating div, optionally to new container
  232. // warning: container CANNOT change size, only position
  233. if (elem) {
  234. this.domElement = ZeroClipboard_TableTools.$(elem);
  235. if (!this.domElement) {
  236. this.hide();
  237. }
  238. }
  239. if (this.domElement && this.div) {
  240. var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement);
  241. var style = this.div.style;
  242. style.left = '' + box.left + 'px';
  243. style.top = '' + box.top + 'px';
  244. }
  245. },
  246. clearText: function () {
  247. // clear the text to be copy / saved
  248. this.clipText = '';
  249. if (this.ready) {
  250. this.movie.clearText();
  251. }
  252. },
  253. appendText: function (newText) {
  254. // append text to that which is to be copied / saved
  255. this.clipText += newText;
  256. if (this.ready) {
  257. this.movie.appendText(newText);
  258. }
  259. },
  260. setText: function (newText) {
  261. // set text to be copied to be copied / saved
  262. this.clipText = newText;
  263. if (this.ready) {
  264. this.movie.setText(newText);
  265. }
  266. },
  267. setFileName: function (newText) {
  268. // set the file name
  269. this.fileName = newText;
  270. if (this.ready) {
  271. this.movie.setFileName(newText);
  272. }
  273. },
  274. setSheetData: function (data) {
  275. // set the xlsx sheet data
  276. if (this.ready) {
  277. this.movie.setSheetData(JSON.stringify(data));
  278. }
  279. },
  280. setAction: function (newText) {
  281. // set action (save or copy)
  282. this.action = newText;
  283. if (this.ready) {
  284. this.movie.setAction(newText);
  285. }
  286. },
  287. addEventListener: function (eventName, func) {
  288. // add user event listener for event
  289. // event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel
  290. eventName = eventName.toString().toLowerCase().replace(/^on/, '');
  291. if (!this.handlers[eventName]) {
  292. this.handlers[eventName] = [];
  293. }
  294. this.handlers[eventName].push(func);
  295. },
  296. setHandCursor: function (enabled) {
  297. // enable hand cursor (true), or default arrow cursor (false)
  298. this.handCursorEnabled = enabled;
  299. if (this.ready) {
  300. this.movie.setHandCursor(enabled);
  301. }
  302. },
  303. setCSSEffects: function (enabled) {
  304. // enable or disable CSS effects on DOM container
  305. this.cssEffects = !!enabled;
  306. },
  307. receiveEvent: function (eventName, args) {
  308. var self;
  309. // receive event from flash
  310. eventName = eventName.toString().toLowerCase().replace(/^on/, '');
  311. // special behavior for certain events
  312. switch (eventName) {
  313. case 'load':
  314. // movie claims it is ready, but in IE this isn't always the case...
  315. // bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function
  316. this.movie = document.getElementById(this.movieId);
  317. if (!this.movie) {
  318. self = this;
  319. setTimeout(function () {
  320. self.receiveEvent('load', null);
  321. }, 1);
  322. return;
  323. }
  324. // firefox on pc needs a "kick" in order to set these in certain cases
  325. if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) {
  326. self = this;
  327. setTimeout(function () {
  328. self.receiveEvent('load', null);
  329. }, 100);
  330. this.ready = true;
  331. return;
  332. }
  333. this.ready = true;
  334. this.movie.clearText();
  335. this.movie.appendText(this.clipText);
  336. this.movie.setFileName(this.fileName);
  337. this.movie.setAction(this.action);
  338. this.movie.setHandCursor(this.handCursorEnabled);
  339. break;
  340. case 'mouseover':
  341. if (this.domElement && this.cssEffects) {
  342. //this.domElement.addClass('hover');
  343. if (this.recoverActive) {
  344. this.domElement.addClass('active');
  345. }
  346. }
  347. break;
  348. case 'mouseout':
  349. if (this.domElement && this.cssEffects) {
  350. this.recoverActive = false;
  351. if (this.domElement.hasClass('active')) {
  352. this.domElement.removeClass('active');
  353. this.recoverActive = true;
  354. }
  355. //this.domElement.removeClass('hover');
  356. }
  357. break;
  358. case 'mousedown':
  359. if (this.domElement && this.cssEffects) {
  360. this.domElement.addClass('active');
  361. }
  362. break;
  363. case 'mouseup':
  364. if (this.domElement && this.cssEffects) {
  365. this.domElement.removeClass('active');
  366. this.recoverActive = false;
  367. }
  368. break;
  369. } // switch eventName
  370. if (this.handlers[eventName]) {
  371. for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) {
  372. var func = this.handlers[eventName][idx];
  373. if (typeof (func) == 'function') {
  374. // actual function reference
  375. func(this, args);
  376. } else if ((typeof (func) == 'object') && (func.length == 2)) {
  377. // PHP style object + method, i.e. [myObject, 'myMethod']
  378. func[0][func[1]](this, args);
  379. } else if (typeof (func) == 'string') {
  380. // name of function
  381. window[func](this, args);
  382. }
  383. } // foreach event handler defined
  384. } // user defined handler for event
  385. }
  386. };
  387. ZeroClipboard_TableTools.hasFlash = function () {
  388. try {
  389. var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
  390. if (fo) {
  391. return true;
  392. }
  393. } catch (e) {
  394. if (
  395. navigator.mimeTypes &&
  396. navigator.mimeTypes['application/x-shockwave-flash'] !== undefined &&
  397. navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin
  398. ) {
  399. return true;
  400. }
  401. }
  402. return false;
  403. };
  404. // For the Flash binding to work, ZeroClipboard_TableTools must be on the global
  405. // object list
  406. window.ZeroClipboard_TableTools = ZeroClipboard_TableTools;
  407. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  408. * Local (private) functions
  409. */
  410. /**
  411. * If a Buttons instance is initlaised before it is placed into the DOM, Flash
  412. * won't be able to bind to it, so we need to wait until it is available, this
  413. * method abstracts that out.
  414. *
  415. * @param {ZeroClipboard} flash ZeroClipboard instance
  416. * @param {jQuery} node Button
  417. */
  418. var _glue = function (flash, node) {
  419. var id = node.attr('id');
  420. if (node.parents('html').length) {
  421. flash.glue(node[0], '');
  422. } else {
  423. setTimeout(function () {
  424. _glue(flash, node);
  425. }, 500);
  426. }
  427. };
  428. /**
  429. * Get the sheet name for Excel exports.
  430. *
  431. * @param {object} config Button configuration
  432. */
  433. var _sheetname = function (config) {
  434. var sheetName = 'Sheet1';
  435. if (config.sheetName) {
  436. sheetName = config.sheetName.replace(/[\[\]\*\/\\\?\:]/g, '');
  437. }
  438. return sheetName;
  439. };
  440. /**
  441. * Set the flash text. This has to be broken up into chunks as the Javascript /
  442. * Flash bridge has a size limit. There is no indication in the Flash
  443. * documentation what this is, and it probably depends upon the browser.
  444. * Experimentation shows that the point is around 50k when data starts to get
  445. * lost, so an 8K limit used here is safe.
  446. *
  447. * @param {ZeroClipboard} flash ZeroClipboard instance
  448. * @param {string} data Data to send to Flash
  449. */
  450. var _setText = function (flash, data) {
  451. var parts = data.match(/[\s\S]{1,8192}/g) || [];
  452. flash.clearText();
  453. for (var i = 0, len = parts.length; i < len; i++) {
  454. flash.appendText(parts[i]);
  455. }
  456. };
  457. /**
  458. * Get the newline character(s)
  459. *
  460. * @param {object} config Button configuration
  461. * @return {string} Newline character
  462. */
  463. var _newLine = function (config) {
  464. return config.newline ?
  465. config.newline :
  466. navigator.userAgent.match(/Windows/) ?
  467. '\r\n' :
  468. '\n';
  469. };
  470. /**
  471. * Combine the data from the `buttons.exportData` method into a string that
  472. * will be used in the export file.
  473. *
  474. * @param {DataTable.Api} dt DataTables API instance
  475. * @param {object} config Button configuration
  476. * @return {object} The data to export
  477. */
  478. var _exportData = function (dt, config) {
  479. var newLine = _newLine(config);
  480. var data = dt.buttons.exportData(config.exportOptions);
  481. var boundary = config.fieldBoundary;
  482. var separator = config.fieldSeparator;
  483. var reBoundary = new RegExp(boundary, 'g');
  484. var escapeChar = config.escapeChar !== undefined ?
  485. config.escapeChar :
  486. '\\';
  487. var join = function (a) {
  488. var s = '';
  489. // If there is a field boundary, then we might need to escape it in
  490. // the source data
  491. for (var i = 0, ien = a.length; i < ien; i++) {
  492. if (i > 0) {
  493. s += separator;
  494. }
  495. s += boundary ?
  496. boundary + ('' + a[i]).replace(reBoundary, escapeChar + boundary) + boundary :
  497. a[i];
  498. }
  499. return s;
  500. };
  501. var header = config.header ? join(data.header) + newLine : '';
  502. var footer = config.footer && data.footer ? newLine + join(data.footer) : '';
  503. var body = [];
  504. for (var i = 0, ien = data.body.length; i < ien; i++) {
  505. body.push(join(data.body[i]));
  506. }
  507. return {
  508. str: header + body.join(newLine) + footer,
  509. rows: body.length
  510. };
  511. };
  512. // Basic initialisation for the buttons is common between them
  513. var flashButton = {
  514. available: function () {
  515. return ZeroClipboard_TableTools.hasFlash();
  516. },
  517. init: function (dt, button, config) {
  518. // Insert the Flash movie
  519. ZeroClipboard_TableTools.moviePath = DataTable.Buttons.swfPath;
  520. var flash = new ZeroClipboard_TableTools.Client();
  521. flash.setHandCursor(true);
  522. flash.addEventListener('mouseDown', function (client) {
  523. config._fromFlash = true;
  524. dt.button(button[0]).trigger();
  525. config._fromFlash = false;
  526. });
  527. _glue(flash, button);
  528. config._flash = flash;
  529. },
  530. destroy: function (dt, button, config) {
  531. config._flash.destroy();
  532. },
  533. fieldSeparator: ',',
  534. fieldBoundary: '"',
  535. exportOptions: {},
  536. title: '*',
  537. messageTop: '*',
  538. messageBottom: '*',
  539. filename: '*',
  540. extension: '.csv',
  541. header: true,
  542. footer: false
  543. };
  544. /**
  545. * Convert from numeric position to letter for column names in Excel
  546. * @param {int} n Column number
  547. * @return {string} Column letter(s) name
  548. */
  549. function createCellPos(n) {
  550. var ordA = 'A'.charCodeAt(0);
  551. var ordZ = 'Z'.charCodeAt(0);
  552. var len = ordZ - ordA + 1;
  553. var s = "";
  554. while (n >= 0) {
  555. s = String.fromCharCode(n % len + ordA) + s;
  556. n = Math.floor(n / len) - 1;
  557. }
  558. return s;
  559. }
  560. /**
  561. * Create an XML node and add any children, attributes, etc without needing to
  562. * be verbose in the DOM.
  563. *
  564. * @param {object} doc XML document
  565. * @param {string} nodeName Node name
  566. * @param {object} opts Options - can be `attr` (attributes), `children`
  567. * (child nodes) and `text` (text content)
  568. * @return {node} Created node
  569. */
  570. function _createNode(doc, nodeName, opts) {
  571. var tempNode = doc.createElement(nodeName);
  572. if (opts) {
  573. if (opts.attr) {
  574. $(tempNode).attr(opts.attr);
  575. }
  576. if (opts.children) {
  577. $.each(opts.children, function (key, value) {
  578. tempNode.appendChild(value);
  579. });
  580. }
  581. if (opts.text !== null && opts.text !== undefined) {
  582. tempNode.appendChild(doc.createTextNode(opts.text));
  583. }
  584. }
  585. return tempNode;
  586. }
  587. /**
  588. * Get the width for an Excel column based on the contents of that column
  589. * @param {object} data Data for export
  590. * @param {int} col Column index
  591. * @return {int} Column width
  592. */
  593. function _excelColWidth(data, col) {
  594. var max = data.header[col].length;
  595. var len, lineSplit, str;
  596. if (data.footer && data.footer[col].length > max) {
  597. max = data.footer[col].length;
  598. }
  599. for (var i = 0, ien = data.body.length; i < ien; i++) {
  600. var point = data.body[i][col];
  601. str = point !== null && point !== undefined ?
  602. point.toString() :
  603. '';
  604. // If there is a newline character, workout the width of the column
  605. // based on the longest line in the string
  606. if (str.indexOf('\n') !== -1) {
  607. lineSplit = str.split('\n');
  608. lineSplit.sort(function (a, b) {
  609. return b.length - a.length;
  610. });
  611. len = lineSplit[0].length;
  612. } else {
  613. len = str.length;
  614. }
  615. if (len > max) {
  616. max = len;
  617. }
  618. // Max width rather than having potentially massive column widths
  619. if (max > 40) {
  620. return 52; // 40 * 1.3
  621. }
  622. }
  623. max *= 1.3;
  624. // And a min width
  625. return max > 6 ? max : 6;
  626. }
  627. var _serialiser = "";
  628. if (typeof window.XMLSerializer === 'undefined') {
  629. _serialiser = new function () {
  630. this.serializeToString = function (input) {
  631. return input.xml
  632. }
  633. };
  634. } else {
  635. _serialiser = new XMLSerializer();
  636. }
  637. var _ieExcel;
  638. /**
  639. * Convert XML documents in an object to strings
  640. * @param {object} obj XLSX document object
  641. */
  642. function _xlsxToStrings(obj) {
  643. if (_ieExcel === undefined) {
  644. // Detect if we are dealing with IE's _awful_ serialiser by seeing if it
  645. // drop attributes
  646. _ieExcel = _serialiser
  647. .serializeToString(
  648. $.parseXML(excelStrings['xl/worksheets/sheet1.xml'])
  649. )
  650. .indexOf('xmlns:r') === -1;
  651. }
  652. $.each(obj, function (name, val) {
  653. if ($.isPlainObject(val)) {
  654. _xlsxToStrings(val);
  655. } else {
  656. if (_ieExcel) {
  657. // IE's XML serialiser will drop some name space attributes from
  658. // from the root node, so we need to save them. Do this by
  659. // replacing the namespace nodes with a regular attribute that
  660. // we convert back when serialised. Edge does not have this
  661. // issue
  662. var worksheet = val.childNodes[0];
  663. var i, ien;
  664. var attrs = [];
  665. for (i = worksheet.attributes.length - 1; i >= 0; i--) {
  666. var attrName = worksheet.attributes[i].nodeName;
  667. var attrValue = worksheet.attributes[i].nodeValue;
  668. if (attrName.indexOf(':') !== -1) {
  669. attrs.push({name: attrName, value: attrValue});
  670. worksheet.removeAttribute(attrName);
  671. }
  672. }
  673. for (i = 0, ien = attrs.length; i < ien; i++) {
  674. var attr = val.createAttribute(attrs[i].name.replace(':', '_dt_b_namespace_token_'));
  675. attr.value = attrs[i].value;
  676. worksheet.setAttributeNode(attr);
  677. }
  678. }
  679. var str = _serialiser.serializeToString(val);
  680. // Fix IE's XML
  681. if (_ieExcel) {
  682. // IE doesn't include the XML declaration
  683. if (str.indexOf('<?xml') === -1) {
  684. str = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' + str;
  685. }
  686. // Return namespace attributes to being as such
  687. str = str.replace(/_dt_b_namespace_token_/g, ':');
  688. }
  689. // Safari, IE and Edge will put empty name space attributes onto
  690. // various elements making them useless. This strips them out
  691. str = str.replace(/<([^<>]*?) xmlns=""([^<>]*?)>/g, '<$1 $2>');
  692. obj[name] = str;
  693. }
  694. });
  695. }
  696. // Excel - Pre-defined strings to build a basic XLSX file
  697. var excelStrings = {
  698. "_rels/.rels":
  699. '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
  700. '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
  701. '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>' +
  702. '</Relationships>',
  703. "xl/_rels/workbook.xml.rels":
  704. '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
  705. '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
  706. '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>' +
  707. '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>' +
  708. '</Relationships>',
  709. "[Content_Types].xml":
  710. '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
  711. '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">' +
  712. '<Default Extension="xml" ContentType="application/xml" />' +
  713. '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml" />' +
  714. '<Default Extension="jpeg" ContentType="image/jpeg" />' +
  715. '<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml" />' +
  716. '<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml" />' +
  717. '<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml" />' +
  718. '</Types>',
  719. "xl/workbook.xml":
  720. '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
  721. '<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' +
  722. '<fileVersion appName="xl" lastEdited="5" lowestEdited="5" rupBuild="24816"/>' +
  723. '<workbookPr showInkAnnotation="0" autoCompressPictures="0"/>' +
  724. '<bookViews>' +
  725. '<workbookView xWindow="0" yWindow="0" windowWidth="25600" windowHeight="19020" tabRatio="500"/>' +
  726. '</bookViews>' +
  727. '<sheets>' +
  728. '<sheet name="" sheetId="1" r:id="rId1"/>' +
  729. '</sheets>' +
  730. '</workbook>',
  731. "xl/worksheets/sheet1.xml":
  732. '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
  733. '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x14ac" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac">' +
  734. '<sheetData/>' +
  735. '<mergeCells count="0"/>' +
  736. '</worksheet>',
  737. "xl/styles.xml":
  738. '<?xml version="1.0" encoding="UTF-8"?>' +
  739. '<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x14ac" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac">' +
  740. '<numFmts count="6">' +
  741. '<numFmt numFmtId="164" formatCode="#,##0.00_-\ [$$-45C]"/>' +
  742. '<numFmt numFmtId="165" formatCode="&quot;£&quot;#,##0.00"/>' +
  743. '<numFmt numFmtId="166" formatCode="[$€-2]\ #,##0.00"/>' +
  744. '<numFmt numFmtId="167" formatCode="0.0%"/>' +
  745. '<numFmt numFmtId="168" formatCode="#,##0;(#,##0)"/>' +
  746. '<numFmt numFmtId="169" formatCode="#,##0.00;(#,##0.00)"/>' +
  747. '</numFmts>' +
  748. '<fonts count="5" x14ac:knownFonts="1">' +
  749. '<font>' +
  750. '<sz val="11" />' +
  751. '<name val="Calibri" />' +
  752. '</font>' +
  753. '<font>' +
  754. '<sz val="11" />' +
  755. '<name val="Calibri" />' +
  756. '<color rgb="FFFFFFFF" />' +
  757. '</font>' +
  758. '<font>' +
  759. '<sz val="11" />' +
  760. '<name val="Calibri" />' +
  761. '<b />' +
  762. '</font>' +
  763. '<font>' +
  764. '<sz val="11" />' +
  765. '<name val="Calibri" />' +
  766. '<i />' +
  767. '</font>' +
  768. '<font>' +
  769. '<sz val="11" />' +
  770. '<name val="Calibri" />' +
  771. '<u />' +
  772. '</font>' +
  773. '</fonts>' +
  774. '<fills count="6">' +
  775. '<fill>' +
  776. '<patternFill patternType="none" />' +
  777. '</fill>' +
  778. '<fill>' + // Excel appears to use this as a dotted background regardless of values but
  779. '<patternFill patternType="none" />' + // to be valid to the schema, use a patternFill
  780. '</fill>' +
  781. '<fill>' +
  782. '<patternFill patternType="solid">' +
  783. '<fgColor rgb="FFD9D9D9" />' +
  784. '<bgColor indexed="64" />' +
  785. '</patternFill>' +
  786. '</fill>' +
  787. '<fill>' +
  788. '<patternFill patternType="solid">' +
  789. '<fgColor rgb="FFD99795" />' +
  790. '<bgColor indexed="64" />' +
  791. '</patternFill>' +
  792. '</fill>' +
  793. '<fill>' +
  794. '<patternFill patternType="solid">' +
  795. '<fgColor rgb="ffc6efce" />' +
  796. '<bgColor indexed="64" />' +
  797. '</patternFill>' +
  798. '</fill>' +
  799. '<fill>' +
  800. '<patternFill patternType="solid">' +
  801. '<fgColor rgb="ffc6cfef" />' +
  802. '<bgColor indexed="64" />' +
  803. '</patternFill>' +
  804. '</fill>' +
  805. '</fills>' +
  806. '<borders count="2">' +
  807. '<border>' +
  808. '<left />' +
  809. '<right />' +
  810. '<top />' +
  811. '<bottom />' +
  812. '<diagonal />' +
  813. '</border>' +
  814. '<border diagonalUp="false" diagonalDown="false">' +
  815. '<left style="thin">' +
  816. '<color auto="1" />' +
  817. '</left>' +
  818. '<right style="thin">' +
  819. '<color auto="1" />' +
  820. '</right>' +
  821. '<top style="thin">' +
  822. '<color auto="1" />' +
  823. '</top>' +
  824. '<bottom style="thin">' +
  825. '<color auto="1" />' +
  826. '</bottom>' +
  827. '<diagonal />' +
  828. '</border>' +
  829. '</borders>' +
  830. '<cellStyleXfs count="1">' +
  831. '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" />' +
  832. '</cellStyleXfs>' +
  833. '<cellXfs count="61">' +
  834. '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  835. '<xf numFmtId="0" fontId="1" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  836. '<xf numFmtId="0" fontId="2" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  837. '<xf numFmtId="0" fontId="3" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  838. '<xf numFmtId="0" fontId="4" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  839. '<xf numFmtId="0" fontId="0" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  840. '<xf numFmtId="0" fontId="1" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  841. '<xf numFmtId="0" fontId="2" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  842. '<xf numFmtId="0" fontId="3" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  843. '<xf numFmtId="0" fontId="4" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  844. '<xf numFmtId="0" fontId="0" fillId="3" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  845. '<xf numFmtId="0" fontId="1" fillId="3" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  846. '<xf numFmtId="0" fontId="2" fillId="3" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  847. '<xf numFmtId="0" fontId="3" fillId="3" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  848. '<xf numFmtId="0" fontId="4" fillId="3" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  849. '<xf numFmtId="0" fontId="0" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  850. '<xf numFmtId="0" fontId="1" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  851. '<xf numFmtId="0" fontId="2" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  852. '<xf numFmtId="0" fontId="3" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  853. '<xf numFmtId="0" fontId="4" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  854. '<xf numFmtId="0" fontId="0" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  855. '<xf numFmtId="0" fontId="1" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  856. '<xf numFmtId="0" fontId="2" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  857. '<xf numFmtId="0" fontId="3" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  858. '<xf numFmtId="0" fontId="4" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>' +
  859. '<xf numFmtId="0" fontId="0" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  860. '<xf numFmtId="0" fontId="1" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  861. '<xf numFmtId="0" fontId="2" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  862. '<xf numFmtId="0" fontId="3" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  863. '<xf numFmtId="0" fontId="4" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  864. '<xf numFmtId="0" fontId="0" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  865. '<xf numFmtId="0" fontId="1" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  866. '<xf numFmtId="0" fontId="2" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  867. '<xf numFmtId="0" fontId="3" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  868. '<xf numFmtId="0" fontId="4" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  869. '<xf numFmtId="0" fontId="0" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  870. '<xf numFmtId="0" fontId="1" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  871. '<xf numFmtId="0" fontId="2" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  872. '<xf numFmtId="0" fontId="3" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  873. '<xf numFmtId="0" fontId="4" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  874. '<xf numFmtId="0" fontId="0" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  875. '<xf numFmtId="0" fontId="1" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  876. '<xf numFmtId="0" fontId="2" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  877. '<xf numFmtId="0" fontId="3" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  878. '<xf numFmtId="0" fontId="4" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  879. '<xf numFmtId="0" fontId="0" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  880. '<xf numFmtId="0" fontId="1" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  881. '<xf numFmtId="0" fontId="2" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  882. '<xf numFmtId="0" fontId="3" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  883. '<xf numFmtId="0" fontId="4" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>' +
  884. '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1">' +
  885. '<alignment horizontal="left"/>' +
  886. '</xf>' +
  887. '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1">' +
  888. '<alignment horizontal="center"/>' +
  889. '</xf>' +
  890. '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1">' +
  891. '<alignment horizontal="right"/>' +
  892. '</xf>' +
  893. '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1">' +
  894. '<alignment horizontal="fill"/>' +
  895. '</xf>' +
  896. '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1">' +
  897. '<alignment textRotation="90"/>' +
  898. '</xf>' +
  899. '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1">' +
  900. '<alignment wrapText="1"/>' +
  901. '</xf>' +
  902. '<xf numFmtId="9" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/>' +
  903. '<xf numFmtId="164" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/>' +
  904. '<xf numFmtId="165" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/>' +
  905. '<xf numFmtId="166" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/>' +
  906. '<xf numFmtId="167" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/>' +
  907. '<xf numFmtId="168" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/>' +
  908. '<xf numFmtId="169" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/>' +
  909. '<xf numFmtId="3" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/>' +
  910. '<xf numFmtId="4" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/>' +
  911. '</cellXfs>' +
  912. '<cellStyles count="1">' +
  913. '<cellStyle name="Normal" xfId="0" builtinId="0" />' +
  914. '</cellStyles>' +
  915. '<dxfs count="0" />' +
  916. '<tableStyles count="0" defaultTableStyle="TableStyleMedium9" defaultPivotStyle="PivotStyleMedium4" />' +
  917. '</styleSheet>'
  918. };
  919. // Note we could use 3 `for` loops for the styles, but when gzipped there is
  920. // virtually no difference in size, since the above can be easily compressed
  921. // Pattern matching for special number formats. Perhaps this should be exposed
  922. // via an API in future?
  923. var _excelSpecials = [
  924. {
  925. match: /^\-?\d+\.\d%$/, style: 60, fmt: function (d) {
  926. return d / 100;
  927. }
  928. }, // Precent with d.p.
  929. {
  930. match: /^\-?\d+\.?\d*%$/, style: 56, fmt: function (d) {
  931. return d / 100;
  932. }
  933. }, // Percent
  934. {match: /^\-?\$[\d,]+.?\d*$/, style: 57}, // Dollars
  935. {match: /^\-?£[\d,]+.?\d*$/, style: 58}, // Pounds
  936. {match: /^\-?€[\d,]+.?\d*$/, style: 59}, // Euros
  937. {
  938. match: /^\([\d,]+\)$/, style: 61, fmt: function (d) {
  939. return -1 * d.replace(/[\(\)]/g, '');
  940. }
  941. }, // Negative numbers indicated by brackets
  942. {
  943. match: /^\([\d,]+\.\d{2}\)$/, style: 62, fmt: function (d) {
  944. return -1 * d.replace(/[\(\)]/g, '');
  945. }
  946. }, // Negative numbers indicated by brackets - 2d.p.
  947. {match: /^[\d,]+$/, style: 63}, // Numbers with thousand separators
  948. {match: /^[\d,]+\.\d{2}$/, style: 64} // Numbers with 2d.p. and thousands separators
  949. ];
  950. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  951. * DataTables options and methods
  952. */
  953. // Set the default SWF path
  954. DataTable.Buttons.swfPath = '//cdn.datatables.net/buttons/' + DataTable.Buttons.version + '/swf/flashExport.swf';
  955. // Method to allow Flash buttons to be resized when made visible - as they are
  956. // of zero height and width if initialised hidden
  957. DataTable.Api.register('buttons.resize()', function () {
  958. $.each(ZeroClipboard_TableTools.clients, function (i, client) {
  959. if (client.domElement !== undefined && client.domElement.parentNode) {
  960. client.positionElement();
  961. }
  962. });
  963. });
  964. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  965. * Button definitions
  966. */
  967. // Copy to clipboard
  968. DataTable.ext.buttons.copyFlash = $.extend({}, flashButton, {
  969. className: 'buttons-copy buttons-flash',
  970. text: function (dt) {
  971. return dt.i18n('buttons.copy', 'Copy');
  972. },
  973. action: function (e, dt, button, config) {
  974. // Check that the trigger did actually occur due to a Flash activation
  975. if (!config._fromFlash) {
  976. return;
  977. }
  978. this.processing(true);
  979. var flash = config._flash;
  980. var exportData = _exportData(dt, config);
  981. var info = dt.buttons.exportInfo(config);
  982. var newline = _newLine(config);
  983. var output = exportData.str;
  984. if (info.title) {
  985. output = info.title + newline + newline + output;
  986. }
  987. if (info.messageTop) {
  988. output = info.messageTop + newline + newline + output;
  989. }
  990. if (info.messageBottom) {
  991. output = output + newline + newline + info.messageBottom;
  992. }
  993. if (config.customize) {
  994. output = config.customize(output, config, dt);
  995. }
  996. flash.setAction('copy');
  997. _setText(flash, output);
  998. this.processing(false);
  999. dt.buttons.info(
  1000. dt.i18n('buttons.copyTitle', 'Copy to clipboard'),
  1001. dt.i18n('buttons.copySuccess', {
  1002. _: 'Copied %d rows to clipboard',
  1003. 1: 'Copied 1 row to clipboard'
  1004. }, data.rows),
  1005. 3000
  1006. );
  1007. },
  1008. fieldSeparator: '\t',
  1009. fieldBoundary: ''
  1010. });
  1011. // CSV save file
  1012. DataTable.ext.buttons.csvFlash = $.extend({}, flashButton, {
  1013. className: 'buttons-csv buttons-flash',
  1014. text: function (dt) {
  1015. return dt.i18n('buttons.csv', 'CSV');
  1016. },
  1017. action: function (e, dt, button, config) {
  1018. // Set the text
  1019. var flash = config._flash;
  1020. var data = _exportData(dt, config);
  1021. var info = dt.buttons.exportInfo(config);
  1022. var output = config.customize ?
  1023. config.customize(data.str, config, dt) :
  1024. data.str;
  1025. flash.setAction('csv');
  1026. flash.setFileName(info.filename);
  1027. _setText(flash, output);
  1028. },
  1029. escapeChar: '"'
  1030. });
  1031. // Excel save file - this is really a CSV file using UTF-8 that Excel can read
  1032. DataTable.ext.buttons.excelFlash = $.extend({}, flashButton, {
  1033. className: 'buttons-excel buttons-flash',
  1034. text: function (dt) {
  1035. return dt.i18n('buttons.excel', 'Excel');
  1036. },
  1037. action: function (e, dt, button, config) {
  1038. this.processing(true);
  1039. var flash = config._flash;
  1040. var rowPos = 0;
  1041. var rels = $.parseXML(excelStrings['xl/worksheets/sheet1.xml']); //Parses xml
  1042. var relsGet = rels.getElementsByTagName("sheetData")[0];
  1043. var xlsx = {
  1044. _rels: {
  1045. ".rels": $.parseXML(excelStrings['_rels/.rels'])
  1046. },
  1047. xl: {
  1048. _rels: {
  1049. "workbook.xml.rels": $.parseXML(excelStrings['xl/_rels/workbook.xml.rels'])
  1050. },
  1051. "workbook.xml": $.parseXML(excelStrings['xl/workbook.xml']),
  1052. "styles.xml": $.parseXML(excelStrings['xl/styles.xml']),
  1053. "worksheets": {
  1054. "sheet1.xml": rels
  1055. }
  1056. },
  1057. "[Content_Types].xml": $.parseXML(excelStrings['[Content_Types].xml'])
  1058. };
  1059. var data = dt.buttons.exportData(config.exportOptions);
  1060. var currentRow, rowNode;
  1061. var addRow = function (row) {
  1062. currentRow = rowPos + 1;
  1063. rowNode = _createNode(rels, "row", {attr: {r: currentRow}});
  1064. for (var i = 0, ien = row.length; i < ien; i++) {
  1065. // Concat both the Cell Columns as a letter and the Row of the cell.
  1066. var cellId = createCellPos(i) + '' + currentRow;
  1067. var cell = null;
  1068. // For null, undefined of blank cell, continue so it doesn't create the _createNode
  1069. if (row[i] === null || row[i] === undefined || row[i] === '') {
  1070. if (config.createEmptyCells === true) {
  1071. row[i] = '';
  1072. } else {
  1073. continue;
  1074. }
  1075. }
  1076. row[i] = typeof row[i].trim === 'function'
  1077. ? row[i].trim()
  1078. : row[i];
  1079. // Special number formatting options
  1080. for (var j = 0, jen = _excelSpecials.length; j < jen; j++) {
  1081. var special = _excelSpecials[j];
  1082. // TODO Need to provide the ability for the specials to say
  1083. // if they are returning a string, since at the moment it is
  1084. // assumed to be a number
  1085. if (row[i].match && !row[i].match(/^0\d+/) && row[i].match(special.match)) {
  1086. var val = row[i].replace(/[^\d\.\-]/g, '');
  1087. if (special.fmt) {
  1088. val = special.fmt(val);
  1089. }
  1090. cell = _createNode(rels, 'c', {
  1091. attr: {
  1092. r: cellId,
  1093. s: special.style
  1094. },
  1095. children: [
  1096. _createNode(rels, 'v', {text: val})
  1097. ]
  1098. });
  1099. break;
  1100. }
  1101. }
  1102. if (!cell) {
  1103. if (typeof row[i] === 'number' || (
  1104. row[i].match &&
  1105. row[i].match(/^-?\d+(\.\d+)?$/) &&
  1106. !row[i].match(/^0\d+/))
  1107. ) {
  1108. // Detect numbers - don't match numbers with leading zeros
  1109. // or a negative anywhere but the start
  1110. cell = _createNode(rels, 'c', {
  1111. attr: {
  1112. t: 'n',
  1113. r: cellId
  1114. },
  1115. children: [
  1116. _createNode(rels, 'v', {text: row[i]})
  1117. ]
  1118. });
  1119. } else {
  1120. // String output - replace non standard characters for text output
  1121. var text = !row[i].replace ?
  1122. row[i] :
  1123. row[i].replace(/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F-\x9F]/g, '');
  1124. cell = _createNode(rels, 'c', {
  1125. attr: {
  1126. t: 'inlineStr',
  1127. r: cellId
  1128. },
  1129. children: {
  1130. row: _createNode(rels, 'is', {
  1131. children: {
  1132. row: _createNode(rels, 't', {
  1133. text: text
  1134. })
  1135. }
  1136. })
  1137. }
  1138. });
  1139. }
  1140. }
  1141. rowNode.appendChild(cell);
  1142. }
  1143. relsGet.appendChild(rowNode);
  1144. rowPos++;
  1145. };
  1146. $('sheets sheet', xlsx.xl['workbook.xml']).attr('name', _sheetname(config));
  1147. if (config.customizeData) {
  1148. config.customizeData(data);
  1149. }
  1150. var mergeCells = function (row, colspan) {
  1151. var mergeCells = $('mergeCells', rels);
  1152. mergeCells[0].appendChild(_createNode(rels, 'mergeCell', {
  1153. attr: {
  1154. ref: 'A' + row + ':' + createCellPos(colspan) + row
  1155. }
  1156. }));
  1157. mergeCells.attr('count', mergeCells.attr('count') + 1);
  1158. $('row:eq(' + (row - 1) + ') c', rels).attr('s', '51'); // centre
  1159. };
  1160. // Title and top messages
  1161. var exportInfo = dt.buttons.exportInfo(config);
  1162. if (exportInfo.title) {
  1163. addRow([exportInfo.title], rowPos);
  1164. mergeCells(rowPos, data.header.length - 1);
  1165. }
  1166. if (exportInfo.messageTop) {
  1167. addRow([exportInfo.messageTop], rowPos);
  1168. mergeCells(rowPos, data.header.length - 1);
  1169. }
  1170. // Table itself
  1171. if (config.header) {
  1172. addRow(data.header, rowPos);
  1173. $('row:last c', rels).attr('s', '2'); // bold
  1174. }
  1175. for (var n = 0, ie = data.body.length; n < ie; n++) {
  1176. addRow(data.body[n], rowPos);
  1177. }
  1178. if (config.footer && data.footer) {
  1179. addRow(data.footer, rowPos);
  1180. $('row:last c', rels).attr('s', '2'); // bold
  1181. }
  1182. // Below the table
  1183. if (exportInfo.messageBottom) {
  1184. addRow([exportInfo.messageBottom], rowPos);
  1185. mergeCells(rowPos, data.header.length - 1);
  1186. }
  1187. // Set column widths
  1188. var cols = _createNode(rels, 'cols');
  1189. $('worksheet', rels).prepend(cols);
  1190. for (var i = 0, ien = data.header.length; i < ien; i++) {
  1191. cols.appendChild(_createNode(rels, 'col', {
  1192. attr: {
  1193. min: i + 1,
  1194. max: i + 1,
  1195. width: _excelColWidth(data, i),
  1196. customWidth: 1
  1197. }
  1198. }));
  1199. }
  1200. // Let the developer customise the document if they want to
  1201. if (config.customize) {
  1202. config.customize(xlsx, config, dt);
  1203. }
  1204. _xlsxToStrings(xlsx);
  1205. flash.setAction('excel');
  1206. flash.setFileName(exportInfo.filename);
  1207. flash.setSheetData(xlsx);
  1208. _setText(flash, '');
  1209. this.processing(false);
  1210. },
  1211. extension: '.xlsx',
  1212. createEmptyCells: false
  1213. });
  1214. // PDF export
  1215. DataTable.ext.buttons.pdfFlash = $.extend({}, flashButton, {
  1216. className: 'buttons-pdf buttons-flash',
  1217. text: function (dt) {
  1218. return dt.i18n('buttons.pdf', 'PDF');
  1219. },
  1220. action: function (e, dt, button, config) {
  1221. this.processing(true);
  1222. // Set the text
  1223. var flash = config._flash;
  1224. var data = dt.buttons.exportData(config.exportOptions);
  1225. var info = dt.buttons.exportInfo(config);
  1226. var totalWidth = dt.table().node().offsetWidth;
  1227. // Calculate the column width ratios for layout of the table in the PDF
  1228. var ratios = dt.columns(config.columns).indexes().map(function (idx) {
  1229. return dt.column(idx).header().offsetWidth / totalWidth;
  1230. });
  1231. flash.setAction('pdf');
  1232. flash.setFileName(info.filename);
  1233. _setText(flash, JSON.stringify({
  1234. title: info.title || '',
  1235. messageTop: info.messageTop || '',
  1236. messageBottom: info.messageBottom || '',
  1237. colWidth: ratios.toArray(),
  1238. orientation: config.orientation,
  1239. size: config.pageSize,
  1240. header: config.header ? data.header : null,
  1241. footer: config.footer ? data.footer : null,
  1242. body: data.body
  1243. }));
  1244. this.processing(false);
  1245. },
  1246. extension: '.pdf',
  1247. orientation: 'portrait',
  1248. pageSize: 'A4',
  1249. newline: '\n'
  1250. });
  1251. return DataTable.Buttons;
  1252. }));