No Description

buttons.flash.js 45KB

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