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

1442 строки
45KB

  1. /*!
  2. * Flash export buttons for Buttons and DataTables.
  3. * 2015 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 file name for an exported file.
  424. *
  425. * @param {object} config Button configuration
  426. * @param {boolean} incExtension Include the file name extension
  427. */
  428. var _filename = function ( config, incExtension )
  429. {
  430. // Backwards compatibility
  431. var filename = config.filename === '*' && config.title !== '*' && config.title !== undefined ?
  432. config.title :
  433. config.filename;
  434. if ( typeof filename === 'function' ) {
  435. filename = filename();
  436. }
  437. if ( filename.indexOf( '*' ) !== -1 ) {
  438. filename = $.trim( filename.replace( '*', $('title').text() ) );
  439. }
  440. // Strip characters which the OS will object to
  441. filename = filename.replace(/[^a-zA-Z0-9_\u00A1-\uFFFF\.,\-_ !\(\)]/g, "");
  442. return incExtension === undefined || incExtension === true ?
  443. filename+config.extension :
  444. filename;
  445. };
  446. /**
  447. * Get the sheet name for Excel exports.
  448. *
  449. * @param {object} config Button configuration
  450. */
  451. var _sheetname = function ( config )
  452. {
  453. var sheetName = 'Sheet1';
  454. if ( config.sheetName ) {
  455. sheetName = config.sheetName.replace(/[\[\]\*\/\\\?\:]/g, '');
  456. }
  457. return sheetName;
  458. };
  459. /**
  460. * Get the title for an exported file.
  461. *
  462. * @param {object} config Button configuration
  463. */
  464. var _title = function ( config )
  465. {
  466. var title = config.title;
  467. if ( typeof title === 'function' ) {
  468. title = title();
  469. }
  470. return title.indexOf( '*' ) !== -1 ?
  471. title.replace( '*', $('title').text() || 'Exported data' ) :
  472. title;
  473. };
  474. /**
  475. * Set the flash text. This has to be broken up into chunks as the Javascript /
  476. * Flash bridge has a size limit. There is no indication in the Flash
  477. * documentation what this is, and it probably depends upon the browser.
  478. * Experimentation shows that the point is around 50k when data starts to get
  479. * lost, so an 8K limit used here is safe.
  480. *
  481. * @param {ZeroClipboard} flash ZeroClipboard instance
  482. * @param {string} data Data to send to Flash
  483. */
  484. var _setText = function ( flash, data )
  485. {
  486. var parts = data.match(/[\s\S]{1,8192}/g) || [];
  487. flash.clearText();
  488. for ( var i=0, len=parts.length ; i<len ; i++ )
  489. {
  490. flash.appendText( parts[i] );
  491. }
  492. };
  493. /**
  494. * Get the newline character(s)
  495. *
  496. * @param {object} config Button configuration
  497. * @return {string} Newline character
  498. */
  499. var _newLine = function ( config )
  500. {
  501. return config.newline ?
  502. config.newline :
  503. navigator.userAgent.match(/Windows/) ?
  504. '\r\n' :
  505. '\n';
  506. };
  507. /**
  508. * Combine the data from the `buttons.exportData` method into a string that
  509. * will be used in the export file.
  510. *
  511. * @param {DataTable.Api} dt DataTables API instance
  512. * @param {object} config Button configuration
  513. * @return {object} The data to export
  514. */
  515. var _exportData = function ( dt, config )
  516. {
  517. var newLine = _newLine( config );
  518. var data = dt.buttons.exportData( config.exportOptions );
  519. var boundary = config.fieldBoundary;
  520. var separator = config.fieldSeparator;
  521. var reBoundary = new RegExp( boundary, 'g' );
  522. var escapeChar = config.escapeChar !== undefined ?
  523. config.escapeChar :
  524. '\\';
  525. var join = function ( a ) {
  526. var s = '';
  527. // If there is a field boundary, then we might need to escape it in
  528. // the source data
  529. for ( var i=0, ien=a.length ; i<ien ; i++ ) {
  530. if ( i > 0 ) {
  531. s += separator;
  532. }
  533. s += boundary ?
  534. boundary + ('' + a[i]).replace( reBoundary, escapeChar+boundary ) + boundary :
  535. a[i];
  536. }
  537. return s;
  538. };
  539. var header = config.header ? join( data.header )+newLine : '';
  540. var footer = config.footer && data.footer ? newLine+join( data.footer ) : '';
  541. var body = [];
  542. for ( var i=0, ien=data.body.length ; i<ien ; i++ ) {
  543. body.push( join( data.body[i] ) );
  544. }
  545. return {
  546. str: header + body.join( newLine ) + footer,
  547. rows: body.length
  548. };
  549. };
  550. // Basic initialisation for the buttons is common between them
  551. var flashButton = {
  552. available: function () {
  553. return ZeroClipboard_TableTools.hasFlash();
  554. },
  555. init: function ( dt, button, config ) {
  556. // Insert the Flash movie
  557. ZeroClipboard_TableTools.moviePath = DataTable.Buttons.swfPath;
  558. var flash = new ZeroClipboard_TableTools.Client();
  559. flash.setHandCursor( true );
  560. flash.addEventListener('mouseDown', function(client) {
  561. config._fromFlash = true;
  562. dt.button( button[0] ).trigger();
  563. config._fromFlash = false;
  564. } );
  565. _glue( flash, button );
  566. config._flash = flash;
  567. },
  568. destroy: function ( dt, button, config ) {
  569. config._flash.destroy();
  570. },
  571. fieldSeparator: ',',
  572. fieldBoundary: '"',
  573. exportOptions: {},
  574. title: '*',
  575. filename: '*',
  576. extension: '.csv',
  577. header: true,
  578. footer: false
  579. };
  580. /**
  581. * Convert from numeric position to letter for column names in Excel
  582. * @param {int} n Column number
  583. * @return {string} Column letter(s) name
  584. */
  585. function createCellPos( n ){
  586. var ordA = 'A'.charCodeAt(0);
  587. var ordZ = 'Z'.charCodeAt(0);
  588. var len = ordZ - ordA + 1;
  589. var s = "";
  590. while( n >= 0 ) {
  591. s = String.fromCharCode(n % len + ordA) + s;
  592. n = Math.floor(n / len) - 1;
  593. }
  594. return s;
  595. }
  596. /**
  597. * Create an XML node and add any children, attributes, etc without needing to
  598. * be verbose in the DOM.
  599. *
  600. * @param {object} doc XML document
  601. * @param {string} nodeName Node name
  602. * @param {object} opts Options - can be `attr` (attributes), `children`
  603. * (child nodes) and `text` (text content)
  604. * @return {node} Created node
  605. */
  606. function _createNode( doc, nodeName, opts ){
  607. var tempNode = doc.createElement( nodeName );
  608. if ( opts ) {
  609. if ( opts.attr ) {
  610. $(tempNode).attr( opts.attr );
  611. }
  612. if( opts.children ) {
  613. $.each( opts.children, function ( key, value ) {
  614. tempNode.appendChild( value );
  615. });
  616. }
  617. if( opts.text ) {
  618. tempNode.appendChild( doc.createTextNode( opts.text ) );
  619. }
  620. }
  621. return tempNode;
  622. }
  623. /**
  624. * Get the width for an Excel column based on the contents of that column
  625. * @param {object} data Data for export
  626. * @param {int} col Column index
  627. * @return {int} Column width
  628. */
  629. function _excelColWidth( data, col ) {
  630. var max = data.header[col].length;
  631. var len, lineSplit, str;
  632. if ( data.footer && data.footer[col].length > max ) {
  633. max = data.footer[col].length;
  634. }
  635. for ( var i=0, ien=data.body.length ; i<ien ; i++ ) {
  636. var point = data.body[i][col];
  637. str = point !== null && point !== undefined ?
  638. point.toString() :
  639. '';
  640. // If there is a newline character, workout the width of the column
  641. // based on the longest line in the string
  642. if ( str.indexOf('\n') !== -1 ) {
  643. lineSplit = str.split('\n');
  644. lineSplit.sort( function (a, b) {
  645. return b.length - a.length;
  646. } );
  647. len = lineSplit[0].length;
  648. }
  649. else {
  650. len = str.length;
  651. }
  652. if ( len > max ) {
  653. max = len;
  654. }
  655. // Max width rather than having potentially massive column widths
  656. if ( max > 40 ) {
  657. return 52; // 40 * 1.3
  658. }
  659. }
  660. max *= 1.3;
  661. // And a min width
  662. return max > 6 ? max : 6;
  663. }
  664. var _serialiser = "";
  665. if (typeof window.XMLSerializer === 'undefined') {
  666. _serialiser = new function () {
  667. this.serializeToString = function (input) {
  668. return input.xml
  669. }
  670. };
  671. } else {
  672. _serialiser = new XMLSerializer();
  673. }
  674. var _ieExcel;
  675. /**
  676. * Convert XML documents in an object to strings
  677. * @param {object} obj XLSX document object
  678. */
  679. function _xlsxToStrings( obj ) {
  680. if ( _ieExcel === undefined ) {
  681. // Detect if we are dealing with IE's _awful_ serialiser by seeing if it
  682. // drop attributes
  683. _ieExcel = _serialiser
  684. .serializeToString(
  685. $.parseXML( excelStrings['xl/worksheets/sheet1.xml'] )
  686. )
  687. .indexOf( 'xmlns:r' ) === -1;
  688. }
  689. $.each( obj, function ( name, val ) {
  690. if ( $.isPlainObject( val ) ) {
  691. _xlsxToStrings( val );
  692. }
  693. else {
  694. if ( _ieExcel ) {
  695. // IE's XML serialiser will drop some name space attributes from
  696. // from the root node, so we need to save them. Do this by
  697. // replacing the namespace nodes with a regular attribute that
  698. // we convert back when serialised. Edge does not have this
  699. // issue
  700. var worksheet = val.childNodes[0];
  701. var i, ien;
  702. var attrs = [];
  703. for ( i=worksheet.attributes.length-1 ; i>=0 ; i-- ) {
  704. var attrName = worksheet.attributes[i].nodeName;
  705. var attrValue = worksheet.attributes[i].nodeValue;
  706. if ( attrName.indexOf( ':' ) !== -1 ) {
  707. attrs.push( { name: attrName, value: attrValue } );
  708. worksheet.removeAttribute( attrName );
  709. }
  710. }
  711. for ( i=0, ien=attrs.length ; i<ien ; i++ ) {
  712. var attr = val.createAttribute( attrs[i].name.replace( ':', '_dt_b_namespace_token_' ) );
  713. attr.value = attrs[i].value;
  714. worksheet.setAttributeNode( attr );
  715. }
  716. }
  717. var str = _serialiser.serializeToString(val);
  718. // Fix IE's XML
  719. if ( _ieExcel ) {
  720. // IE doesn't include the XML declaration
  721. if ( str.indexOf( '<?xml' ) === -1 ) {
  722. str = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+str;
  723. }
  724. // Return namespace attributes to being as such
  725. str = str.replace( /_dt_b_namespace_token_/g, ':' );
  726. }
  727. // Safari, IE and Edge will put empty name space attributes onto
  728. // various elements making them useless. This strips them out
  729. str = str.replace( /<([^<>]*?) xmlns=""([^<>]*?)>/g, '<$1 $2>' );
  730. obj[ name ] = str;
  731. }
  732. } );
  733. }
  734. // Excel - Pre-defined strings to build a basic XLSX file
  735. var excelStrings = {
  736. "_rels/.rels":
  737. '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+
  738. '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'+
  739. '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>'+
  740. '</Relationships>',
  741. "xl/_rels/workbook.xml.rels":
  742. '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+
  743. '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'+
  744. '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>'+
  745. '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>'+
  746. '</Relationships>',
  747. "[Content_Types].xml":
  748. '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+
  749. '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'+
  750. '<Default Extension="xml" ContentType="application/xml" />'+
  751. '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml" />'+
  752. '<Default Extension="jpeg" ContentType="image/jpeg" />'+
  753. '<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml" />'+
  754. '<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml" />'+
  755. '<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml" />'+
  756. '</Types>',
  757. "xl/workbook.xml":
  758. '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+
  759. '<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'+
  760. '<fileVersion appName="xl" lastEdited="5" lowestEdited="5" rupBuild="24816"/>'+
  761. '<workbookPr showInkAnnotation="0" autoCompressPictures="0"/>'+
  762. '<bookViews>'+
  763. '<workbookView xWindow="0" yWindow="0" windowWidth="25600" windowHeight="19020" tabRatio="500"/>'+
  764. '</bookViews>'+
  765. '<sheets>'+
  766. '<sheet name="" sheetId="1" r:id="rId1"/>'+
  767. '</sheets>'+
  768. '</workbook>',
  769. "xl/worksheets/sheet1.xml":
  770. '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+
  771. '<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">'+
  772. '<sheetData/>'+
  773. '</worksheet>',
  774. "xl/styles.xml":
  775. '<?xml version="1.0" encoding="UTF-8"?>'+
  776. '<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">'+
  777. '<numFmts count="6">'+
  778. '<numFmt numFmtId="164" formatCode="#,##0.00_-\ [$$-45C]"/>'+
  779. '<numFmt numFmtId="165" formatCode="&quot;£&quot;#,##0.00"/>'+
  780. '<numFmt numFmtId="166" formatCode="[$€-2]\ #,##0.00"/>'+
  781. '<numFmt numFmtId="167" formatCode="0.0%"/>'+
  782. '<numFmt numFmtId="168" formatCode="#,##0;(#,##0)"/>'+
  783. '<numFmt numFmtId="169" formatCode="#,##0.00;(#,##0.00)"/>'+
  784. '</numFmts>'+
  785. '<fonts count="5" x14ac:knownFonts="1">'+
  786. '<font>'+
  787. '<sz val="11" />'+
  788. '<name val="Calibri" />'+
  789. '</font>'+
  790. '<font>'+
  791. '<sz val="11" />'+
  792. '<name val="Calibri" />'+
  793. '<color rgb="FFFFFFFF" />'+
  794. '</font>'+
  795. '<font>'+
  796. '<sz val="11" />'+
  797. '<name val="Calibri" />'+
  798. '<b />'+
  799. '</font>'+
  800. '<font>'+
  801. '<sz val="11" />'+
  802. '<name val="Calibri" />'+
  803. '<i />'+
  804. '</font>'+
  805. '<font>'+
  806. '<sz val="11" />'+
  807. '<name val="Calibri" />'+
  808. '<u />'+
  809. '</font>'+
  810. '</fonts>'+
  811. '<fills count="6">'+
  812. '<fill>'+
  813. '<patternFill patternType="none" />'+
  814. '</fill>'+
  815. '<fill/>'+ // Excel appears to use this as a dotted background regardless of values
  816. '<fill>'+
  817. '<patternFill patternType="solid">'+
  818. '<fgColor rgb="FFD9D9D9" />'+
  819. '<bgColor indexed="64" />'+
  820. '</patternFill>'+
  821. '</fill>'+
  822. '<fill>'+
  823. '<patternFill patternType="solid">'+
  824. '<fgColor rgb="FFD99795" />'+
  825. '<bgColor indexed="64" />'+
  826. '</patternFill>'+
  827. '</fill>'+
  828. '<fill>'+
  829. '<patternFill patternType="solid">'+
  830. '<fgColor rgb="ffc6efce" />'+
  831. '<bgColor indexed="64" />'+
  832. '</patternFill>'+
  833. '</fill>'+
  834. '<fill>'+
  835. '<patternFill patternType="solid">'+
  836. '<fgColor rgb="ffc6cfef" />'+
  837. '<bgColor indexed="64" />'+
  838. '</patternFill>'+
  839. '</fill>'+
  840. '</fills>'+
  841. '<borders count="2">'+
  842. '<border>'+
  843. '<left />'+
  844. '<right />'+
  845. '<top />'+
  846. '<bottom />'+
  847. '<diagonal />'+
  848. '</border>'+
  849. '<border diagonalUp="false" diagonalDown="false">'+
  850. '<left style="thin">'+
  851. '<color auto="1" />'+
  852. '</left>'+
  853. '<right style="thin">'+
  854. '<color auto="1" />'+
  855. '</right>'+
  856. '<top style="thin">'+
  857. '<color auto="1" />'+
  858. '</top>'+
  859. '<bottom style="thin">'+
  860. '<color auto="1" />'+
  861. '</bottom>'+
  862. '<diagonal />'+
  863. '</border>'+
  864. '</borders>'+
  865. '<cellStyleXfs count="1">'+
  866. '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" />'+
  867. '</cellStyleXfs>'+
  868. '<cellXfs count="61">'+
  869. '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  870. '<xf numFmtId="0" fontId="1" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  871. '<xf numFmtId="0" fontId="2" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  872. '<xf numFmtId="0" fontId="3" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  873. '<xf numFmtId="0" fontId="4" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  874. '<xf numFmtId="0" fontId="0" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  875. '<xf numFmtId="0" fontId="1" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  876. '<xf numFmtId="0" fontId="2" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  877. '<xf numFmtId="0" fontId="3" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  878. '<xf numFmtId="0" fontId="4" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  879. '<xf numFmtId="0" fontId="0" fillId="3" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  880. '<xf numFmtId="0" fontId="1" fillId="3" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  881. '<xf numFmtId="0" fontId="2" fillId="3" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  882. '<xf numFmtId="0" fontId="3" fillId="3" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  883. '<xf numFmtId="0" fontId="4" fillId="3" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  884. '<xf numFmtId="0" fontId="0" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  885. '<xf numFmtId="0" fontId="1" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  886. '<xf numFmtId="0" fontId="2" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  887. '<xf numFmtId="0" fontId="3" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  888. '<xf numFmtId="0" fontId="4" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  889. '<xf numFmtId="0" fontId="0" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  890. '<xf numFmtId="0" fontId="1" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  891. '<xf numFmtId="0" fontId="2" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  892. '<xf numFmtId="0" fontId="3" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  893. '<xf numFmtId="0" fontId="4" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+
  894. '<xf numFmtId="0" fontId="0" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  895. '<xf numFmtId="0" fontId="1" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  896. '<xf numFmtId="0" fontId="2" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  897. '<xf numFmtId="0" fontId="3" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  898. '<xf numFmtId="0" fontId="4" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  899. '<xf numFmtId="0" fontId="0" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  900. '<xf numFmtId="0" fontId="1" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  901. '<xf numFmtId="0" fontId="2" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  902. '<xf numFmtId="0" fontId="3" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  903. '<xf numFmtId="0" fontId="4" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  904. '<xf numFmtId="0" fontId="0" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  905. '<xf numFmtId="0" fontId="1" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  906. '<xf numFmtId="0" fontId="2" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  907. '<xf numFmtId="0" fontId="3" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  908. '<xf numFmtId="0" fontId="4" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  909. '<xf numFmtId="0" fontId="0" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  910. '<xf numFmtId="0" fontId="1" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  911. '<xf numFmtId="0" fontId="2" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  912. '<xf numFmtId="0" fontId="3" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  913. '<xf numFmtId="0" fontId="4" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  914. '<xf numFmtId="0" fontId="0" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  915. '<xf numFmtId="0" fontId="1" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  916. '<xf numFmtId="0" fontId="2" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  917. '<xf numFmtId="0" fontId="3" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  918. '<xf numFmtId="0" fontId="4" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+
  919. '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1">'+
  920. '<alignment horizontal="left"/>'+
  921. '</xf>'+
  922. '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1">'+
  923. '<alignment horizontal="center"/>'+
  924. '</xf>'+
  925. '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1">'+
  926. '<alignment horizontal="right"/>'+
  927. '</xf>'+
  928. '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1">'+
  929. '<alignment horizontal="fill"/>'+
  930. '</xf>'+
  931. '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1">'+
  932. '<alignment textRotation="90"/>'+
  933. '</xf>'+
  934. '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1">'+
  935. '<alignment wrapText="1"/>'+
  936. '</xf>'+
  937. '<xf numFmtId="9" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/>'+
  938. '<xf numFmtId="164" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/>'+
  939. '<xf numFmtId="165" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/>'+
  940. '<xf numFmtId="166" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/>'+
  941. '<xf numFmtId="167" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/>'+
  942. '<xf numFmtId="168" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/>'+
  943. '<xf numFmtId="169" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/>'+
  944. '<xf numFmtId="3" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/>'+
  945. '<xf numFmtId="4" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/>'+
  946. '</cellXfs>'+
  947. '<cellStyles count="1">'+
  948. '<cellStyle name="Normal" xfId="0" builtinId="0" />'+
  949. '</cellStyles>'+
  950. '<dxfs count="0" />'+
  951. '<tableStyles count="0" defaultTableStyle="TableStyleMedium9" defaultPivotStyle="PivotStyleMedium4" />'+
  952. '</styleSheet>'
  953. };
  954. // Note we could use 3 `for` loops for the styles, but when gzipped there is
  955. // virtually no difference in size, since the above can be easily compressed
  956. // Pattern matching for special number formats. Perhaps this should be exposed
  957. // via an API in future?
  958. var _excelSpecials = [
  959. { match: /^\-?\d+\.\d%$/, style: 60, fmt: function (d) { return d/100; } }, // Precent with d.p.
  960. { match: /^\-?\d+\.?\d*%$/, style: 56, fmt: function (d) { return d/100; } }, // Percent
  961. { match: /^\-?\$[\d,]+.?\d*$/, style: 57 }, // Dollars
  962. { match: /^\-?£[\d,]+.?\d*$/, style: 58 }, // Pounds
  963. { match: /^\-?€[\d,]+.?\d*$/, style: 59 }, // Euros
  964. { match: /^\([\d,]+\)$/, style: 61, fmt: function (d) { return -1 * d.replace(/[\(\)]/g, ''); } }, // Negative numbers indicated by brackets
  965. { match: /^\([\d,]+\.\d{2}\)$/, style: 62, fmt: function (d) { return -1 * d.replace(/[\(\)]/g, ''); } }, // Negative numbers indicated by brackets - 2d.p.
  966. { match: /^[\d,]+$/, style: 63 }, // Numbers with thousand separators
  967. { match: /^[\d,]+\.\d{2}$/, style: 64 } // Numbers with 2d.p. and thousands separators
  968. ];
  969. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  970. * DataTables options and methods
  971. */
  972. // Set the default SWF path
  973. DataTable.Buttons.swfPath = '//cdn.datatables.net/buttons/1.2.4/swf/flashExport.swf';
  974. // Method to allow Flash buttons to be resized when made visible - as they are
  975. // of zero height and width if initialised hidden
  976. DataTable.Api.register( 'buttons.resize()', function () {
  977. $.each( ZeroClipboard_TableTools.clients, function ( i, client ) {
  978. if ( client.domElement !== undefined && client.domElement.parentNode ) {
  979. client.positionElement();
  980. }
  981. } );
  982. } );
  983. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  984. * Button definitions
  985. */
  986. // Copy to clipboard
  987. DataTable.ext.buttons.copyFlash = $.extend( {}, flashButton, {
  988. className: 'buttons-copy buttons-flash',
  989. text: function ( dt ) {
  990. return dt.i18n( 'buttons.copy', 'Copy' );
  991. },
  992. action: function ( e, dt, button, config ) {
  993. // Check that the trigger did actually occur due to a Flash activation
  994. if ( ! config._fromFlash ) {
  995. return;
  996. }
  997. this.processing( true );
  998. var flash = config._flash;
  999. var data = _exportData( dt, config );
  1000. var output = config.customize ?
  1001. config.customize( data.str, config ) :
  1002. data.str;
  1003. flash.setAction( 'copy' );
  1004. _setText( flash, output );
  1005. this.processing( false );
  1006. dt.buttons.info(
  1007. dt.i18n( 'buttons.copyTitle', 'Copy to clipboard' ),
  1008. dt.i18n( 'buttons.copySuccess', {
  1009. _: 'Copied %d rows to clipboard',
  1010. 1: 'Copied 1 row to clipboard'
  1011. }, data.rows ),
  1012. 3000
  1013. );
  1014. },
  1015. fieldSeparator: '\t',
  1016. fieldBoundary: ''
  1017. } );
  1018. // CSV save file
  1019. DataTable.ext.buttons.csvFlash = $.extend( {}, flashButton, {
  1020. className: 'buttons-csv buttons-flash',
  1021. text: function ( dt ) {
  1022. return dt.i18n( 'buttons.csv', 'CSV' );
  1023. },
  1024. action: function ( e, dt, button, config ) {
  1025. // Set the text
  1026. var flash = config._flash;
  1027. var data = _exportData( dt, config );
  1028. var output = config.customize ?
  1029. config.customize( data.str, config ) :
  1030. data.str;
  1031. flash.setAction( 'csv' );
  1032. flash.setFileName( _filename( config ) );
  1033. _setText( flash, output );
  1034. },
  1035. escapeChar: '"'
  1036. } );
  1037. // Excel save file - this is really a CSV file using UTF-8 that Excel can read
  1038. DataTable.ext.buttons.excelFlash = $.extend( {}, flashButton, {
  1039. className: 'buttons-excel buttons-flash',
  1040. text: function ( dt ) {
  1041. return dt.i18n( 'buttons.excel', 'Excel' );
  1042. },
  1043. action: function ( e, dt, button, config ) {
  1044. this.processing( true );
  1045. var flash = config._flash;
  1046. var rowPos = 0;
  1047. var rels = $.parseXML( excelStrings['xl/worksheets/sheet1.xml'] ) ; //Parses xml
  1048. var relsGet = rels.getElementsByTagName( "sheetData" )[0];
  1049. var xlsx = {
  1050. _rels: {
  1051. ".rels": $.parseXML( excelStrings['_rels/.rels'] )
  1052. },
  1053. xl: {
  1054. _rels: {
  1055. "workbook.xml.rels": $.parseXML( excelStrings['xl/_rels/workbook.xml.rels'] )
  1056. },
  1057. "workbook.xml": $.parseXML( excelStrings['xl/workbook.xml'] ),
  1058. "styles.xml": $.parseXML( excelStrings['xl/styles.xml'] ),
  1059. "worksheets": {
  1060. "sheet1.xml": rels
  1061. }
  1062. },
  1063. "[Content_Types].xml": $.parseXML( excelStrings['[Content_Types].xml'])
  1064. };
  1065. var data = dt.buttons.exportData( config.exportOptions );
  1066. var currentRow, rowNode;
  1067. var addRow = function ( row ) {
  1068. currentRow = rowPos+1;
  1069. rowNode = _createNode( rels, "row", { attr: {r:currentRow} } );
  1070. for ( var i=0, ien=row.length ; i<ien ; i++ ) {
  1071. // Concat both the Cell Columns as a letter and the Row of the cell.
  1072. var cellId = createCellPos(i) + '' + currentRow;
  1073. var cell = null;
  1074. // For null, undefined of blank cell, continue so it doesn't create the _createNode
  1075. if ( row[i] === null || row[i] === undefined || row[i] === '' ) {
  1076. continue;
  1077. }
  1078. row[i] = $.trim( 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. }
  1120. else {
  1121. // String output - replace non standard characters for text output
  1122. var text = ! row[i].replace ?
  1123. row[i] :
  1124. row[i].replace(/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F-\x9F]/g, '');
  1125. cell = _createNode( rels, 'c', {
  1126. attr: {
  1127. t: 'inlineStr',
  1128. r: cellId
  1129. },
  1130. children:{
  1131. row: _createNode( rels, 'is', {
  1132. children: {
  1133. row: _createNode( rels, 't', {
  1134. text: text
  1135. } )
  1136. }
  1137. } )
  1138. }
  1139. } );
  1140. }
  1141. }
  1142. rowNode.appendChild( cell );
  1143. }
  1144. relsGet.appendChild(rowNode);
  1145. rowPos++;
  1146. };
  1147. $( 'sheets sheet', xlsx.xl['workbook.xml'] ).attr( 'name', _sheetname( config ) );
  1148. if ( config.customizeData ) {
  1149. config.customizeData( data );
  1150. }
  1151. if ( config.header ) {
  1152. addRow( data.header, rowPos );
  1153. $('row c', rels).attr( 's', '2' ); // bold
  1154. }
  1155. for ( var n=0, ie=data.body.length ; n<ie ; n++ ) {
  1156. addRow( data.body[n], rowPos );
  1157. }
  1158. if ( config.footer && data.footer ) {
  1159. addRow( data.footer, rowPos);
  1160. $('row:last c', rels).attr( 's', '2' ); // bold
  1161. }
  1162. // Set column widths
  1163. var cols = _createNode( rels, 'cols' );
  1164. $('worksheet', rels).prepend( cols );
  1165. for ( var i=0, ien=data.header.length ; i<ien ; i++ ) {
  1166. cols.appendChild( _createNode( rels, 'col', {
  1167. attr: {
  1168. min: i+1,
  1169. max: i+1,
  1170. width: _excelColWidth( data, i ),
  1171. customWidth: 1
  1172. }
  1173. } ) );
  1174. }
  1175. // Let the developer customise the document if they want to
  1176. if ( config.customize ) {
  1177. config.customize( xlsx );
  1178. }
  1179. _xlsxToStrings( xlsx );
  1180. flash.setAction( 'excel' );
  1181. flash.setFileName( _filename( config ) );
  1182. flash.setSheetData( xlsx );
  1183. _setText( flash, '' );
  1184. this.processing( false );
  1185. },
  1186. extension: '.xlsx'
  1187. } );
  1188. // PDF export
  1189. DataTable.ext.buttons.pdfFlash = $.extend( {}, flashButton, {
  1190. className: 'buttons-pdf buttons-flash',
  1191. text: function ( dt ) {
  1192. return dt.i18n( 'buttons.pdf', 'PDF' );
  1193. },
  1194. action: function ( e, dt, button, config ) {
  1195. this.processing( true );
  1196. // Set the text
  1197. var flash = config._flash;
  1198. var data = dt.buttons.exportData( config.exportOptions );
  1199. var totalWidth = dt.table().node().offsetWidth;
  1200. // Calculate the column width ratios for layout of the table in the PDF
  1201. var ratios = dt.columns( config.columns ).indexes().map( function ( idx ) {
  1202. return dt.column( idx ).header().offsetWidth / totalWidth;
  1203. } );
  1204. flash.setAction( 'pdf' );
  1205. flash.setFileName( _filename( config ) );
  1206. _setText( flash, JSON.stringify( {
  1207. title: _filename(config, false),
  1208. message: typeof config.message == 'function' ? config.message(dt, button, config) : config.message,
  1209. colWidth: ratios.toArray(),
  1210. orientation: config.orientation,
  1211. size: config.pageSize,
  1212. header: config.header ? data.header : null,
  1213. footer: config.footer ? data.footer : null,
  1214. body: data.body
  1215. } ) );
  1216. this.processing( false );
  1217. },
  1218. extension: '.pdf',
  1219. orientation: 'portrait',
  1220. pageSize: 'A4',
  1221. message: '',
  1222. newline: '\n'
  1223. } );
  1224. return DataTable.Buttons;
  1225. }));