UNPKG

tableexport.jquery.plugin

Version:
1,205 lines (1,018 loc) 98.5 kB
/** * @preserve tableExport.jquery.plugin * * Version 1.10.14 * * Copyright (c) 2015-2020 hhurz, https://github.com/hhurz/tableExport.jquery.plugin * * Based on https://github.com/kayalshri/tableExport.jquery.plugin * * Licensed under the MIT License **/ 'use strict'; (function ($) { $.fn.tableExport = function (options) { var defaults = { csvEnclosure: '"', csvSeparator: ',', csvUseBOM: true, date: { html: 'dd/mm/yyyy' // Date format used in html source. Supported placeholders: dd, mm, yy, yyyy and a arbitrary single separator character }, displayTableName: false, // Deprecated escape: false, // Deprecated exportHiddenCells: false, // true = speed up export of large tables with hidden cells (hidden cells will be exported !) fileName: 'tableExport', htmlContent: false, htmlHyperlink: 'content', // Export the 'content' or the 'href' link of <a> tags unless onCellHtmlHyperlink is not defined ignoreColumn: [], ignoreRow: [], jsonScope: 'all', // One of 'head', 'data', 'all' jspdf: { // jsPDF / jsPDF-AutoTable related options orientation: 'p', unit: 'pt', format: 'a4', // One of jsPDF page formats or 'bestfit' for automatic paper format selection margins: {left: 20, right: 10, top: 10, bottom: 10}, onDocCreated: null, autotable: { styles: { cellPadding: 2, rowHeight: 12, fontSize: 8, fillColor: 255, // Color value or 'inherit' to use css background-color from html table textColor: 50, // Color value or 'inherit' to use css color from html table fontStyle: 'normal', // 'normal', 'bold', 'italic', 'bolditalic' or 'inherit' to use css font-weight and font-style from html table overflow: 'ellipsize', // 'visible', 'hidden', 'ellipsize' or 'linebreak' halign: 'inherit', // 'left', 'center', 'right' or 'inherit' to use css horizontal cell alignment from html table valign: 'middle' // 'top', 'middle', or 'bottom' }, headerStyles: { fillColor: [52, 73, 94], textColor: 255, fontStyle: 'bold', halign: 'inherit', // 'left', 'center', 'right' or 'inherit' to use css horizontal header cell alignment from html table valign: 'middle' // 'top', 'middle', or 'bottom' }, alternateRowStyles: { fillColor: 245 }, tableExport: { doc: null, // jsPDF doc object. If set, an already created doc object will be used to export to onAfterAutotable: null, onBeforeAutotable: null, onAutotableText: null, onTable: null, outputImages: true } } }, mso: { // MS Excel and MS Word related options fileFormat: 'xlshtml', // 'xlshtml' = Excel 2000 html format // 'xmlss' = XML Spreadsheet 2003 file format (XMLSS) // 'xlsx' = Excel 2007 Office Open XML format onMsoNumberFormat: null, // Excel 2000 html format only. See readme.md for more information about msonumberformat pageFormat: 'a4', // Page format used for page orientation pageOrientation: 'portrait', // portrait, landscape (xlshtml format only) rtl: false, // true = Set worksheet option 'DisplayRightToLeft' styles: [], // E.g. ['border-bottom', 'border-top', 'border-left', 'border-right'] worksheetName: '', xslx: { // Specific Excel 2007 XML format settings: formatId: { // XLSX format (id) used to format excel cells. See readme.md: data-tableexport-xlsxformatid date: 14, // formatId or format string (e.g. 'm/d/yy') or function(cell, row, col) {return formatId} numbers: 2 // formatId or format string (e.g. '\"T\"\ #0.00') or function(cell, row, col) {return formatId} } } }, numbers: { html: { decimalMark: '.', // Decimal mark in html source thousandsSeparator: ',' // Thousands separator in html source }, output: { // Set 'output: false' to keep number format of html source in resulting output decimalMark: '.', // Decimal mark in resulting output thousandsSeparator: ',' // Thousands separator in resulting output } }, onAfterSaveToFile: null, // function(data, fileName) onBeforeSaveToFile: null, // saveIt = function(data, fileName, type, charset, encoding): Return false to abort save process onCellData: null, // Text to export = function($cell, row, col, href, cellText, cellType) onCellHtmlData: null, // Text to export = function($cell, row, col, htmlContent) onCellHtmlHyperlink: null, // Text to export = function($cell, row, col, href, cellText) onIgnoreRow: null, // ignoreRow = function($tr, row): Return true to prevent export of the row outputMode: 'file', // 'file', 'string', 'base64' or 'window' (experimental) pdfmake: { enabled: false, // true: use pdfmake instead of jspdf and jspdf-autotable (experimental) docDefinition: { pageOrientation: 'portrait', // 'portrait' or 'landscape' defaultStyle: { font: 'Roboto' // Default is 'Roboto', for an arabic font set this option to 'Mirza' and include mirza_fonts.js } }, fonts: {} }, preserve: { leadingWS: false, // preserve leading white spaces trailingWS: false // preserve trailing white spaces }, preventInjection: true, // Prepend a single quote to cell strings that start with =,+,- or @ to prevent formula injection sql: { tableEnclosure: '`', // If table name or column names contain any characters except letters, numbers, and columnEnclosure: '`' // underscores, usually the name must be delimited by enclosing it in back quotes (`) }, tbodySelector: 'tr', tfootSelector: 'tr', // Set empty ('') to prevent export of tfoot rows theadSelector: 'tr', tableName: 'Table', type: 'csv' // Export format: 'csv', 'tsv', 'txt', 'sql', 'json', 'xml', 'excel', 'doc', 'png' or 'pdf' }; var pageFormats = { // Size in pt of various paper formats. Adopted from jsPDF. 'a0': [2383.94, 3370.39], 'a1': [1683.78, 2383.94], 'a2': [1190.55, 1683.78], 'a3': [841.89, 1190.55], 'a4': [595.28, 841.89], 'a5': [419.53, 595.28], 'a6': [297.64, 419.53], 'a7': [209.76, 297.64], 'a8': [147.40, 209.76], 'a9': [104.88, 147.40], 'a10': [73.70, 104.88], 'b0': [2834.65, 4008.19], 'b1': [2004.09, 2834.65], 'b2': [1417.32, 2004.09], 'b3': [1000.63, 1417.32], 'b4': [708.66, 1000.63], 'b5': [498.90, 708.66], 'b6': [354.33, 498.90], 'b7': [249.45, 354.33], 'b8': [175.75, 249.45], 'b9': [124.72, 175.75], 'b10': [87.87, 124.72], 'c0': [2599.37, 3676.54], 'c1': [1836.85, 2599.37], 'c2': [1298.27, 1836.85], 'c3': [918.43, 1298.27], 'c4': [649.13, 918.43], 'c5': [459.21, 649.13], 'c6': [323.15, 459.21], 'c7': [229.61, 323.15], 'c8': [161.57, 229.61], 'c9': [113.39, 161.57], 'c10': [79.37, 113.39], 'dl': [311.81, 623.62], 'letter': [612, 792], 'government-letter': [576, 756], 'legal': [612, 1008], 'junior-legal': [576, 360], 'ledger': [1224, 792], 'tabloid': [792, 1224], 'credit-card': [153, 243] }; var FONT_ROW_RATIO = 1.15; var el = this; var DownloadEvt = null; var $hrows = []; var $rows = []; var rowIndex = 0; var trData = ''; var colNames = []; var ranges = []; var blob; var $hiddenTableElements = []; var checkCellVisibilty = false; $.extend(true, defaults, options); // Adopt deprecated options if (defaults.type === 'xlsx') { defaults.mso.fileFormat = defaults.type; defaults.type = 'excel'; } if (typeof defaults.excelFileFormat !== 'undefined' && defaults.mso.fileFormat === 'undefined') defaults.mso.fileFormat = defaults.excelFileFormat; if (typeof defaults.excelPageFormat !== 'undefined' && defaults.mso.pageFormat === 'undefined') defaults.mso.pageFormat = defaults.excelPageFormat; if (typeof defaults.excelPageOrientation !== 'undefined' && defaults.mso.pageOrientation === 'undefined') defaults.mso.pageOrientation = defaults.excelPageOrientation; if (typeof defaults.excelRTL !== 'undefined' && defaults.mso.rtl === 'undefined') defaults.mso.rtl = defaults.excelRTL; if (typeof defaults.excelstyles !== 'undefined' && defaults.mso.styles === 'undefined') defaults.mso.styles = defaults.excelstyles; if (typeof defaults.onMsoNumberFormat !== 'undefined' && defaults.mso.onMsoNumberFormat === 'undefined') defaults.mso.onMsoNumberFormat = defaults.onMsoNumberFormat; if (typeof defaults.worksheetName !== 'undefined' && defaults.mso.worksheetName === 'undefined') defaults.mso.worksheetName = defaults.worksheetName; // Check values of some options defaults.mso.pageOrientation = (defaults.mso.pageOrientation.substr(0, 1) === 'l') ? 'landscape' : 'portrait'; defaults.date.html = defaults.date.html || ''; if (defaults.date.html.length) { var patt = []; patt['dd'] = '(3[01]|[12][0-9]|0?[1-9])'; patt['mm'] = '(1[012]|0?[1-9])'; patt['yyyy'] = '((?:1[6-9]|2[0-2])\\d{2})'; patt['yy'] = '(\\d{2})'; var separator = defaults.date.html.match(/[^a-zA-Z0-9]/)[0]; var formatItems = defaults.date.html.toLowerCase().split(separator); defaults.date.regex = '^\\s*'; defaults.date.regex += patt[formatItems[0]]; defaults.date.regex += '(.)'; // separator group defaults.date.regex += patt[formatItems[1]]; defaults.date.regex += '\\2'; // identical separator group defaults.date.regex += patt[formatItems[2]]; defaults.date.regex += '\\s*$'; // e.g. '^\\s*(3[01]|[12][0-9]|0?[1-9])(.)(1[012]|0?[1-9])\\2((?:1[6-9]|2[0-2])\\d{2})\\s*$' defaults.date.pattern = new RegExp(defaults.date.regex, 'g'); var f = formatItems.indexOf('dd') + 1; defaults.date.match_d = f + (f > 1 ? 1 : 0); f = formatItems.indexOf('mm') + 1; defaults.date.match_m = f + (f > 1 ? 1 : 0); f = (formatItems.indexOf('yyyy') >= 0 ? formatItems.indexOf('yyyy') : formatItems.indexOf('yy')) + 1; defaults.date.match_y = f + (f > 1 ? 1 : 0); } colNames = GetColumnNames(el); if (defaults.type === 'csv' || defaults.type === 'tsv' || defaults.type === 'txt') { var csvData = ''; var rowlength = 0; ranges = []; rowIndex = 0; var csvString = function (cell, rowIndex, colIndex) { var result = ''; if (cell !== null) { var dataString = parseString(cell, rowIndex, colIndex); var csvValue = (dataString === null || dataString === '') ? '' : dataString.toString(); if (defaults.type === 'tsv') { if (dataString instanceof Date) dataString.toLocaleString(); // According to http://www.iana.org/assignments/media-types/text/tab-separated-values // are fields that contain tabs not allowable in tsv encoding result = replaceAll(csvValue, '\t', ' '); } else { // Takes a string and encapsulates it (by default in double-quotes) if it // contains the csv field separator, spaces, or linebreaks. if (dataString instanceof Date) result = defaults.csvEnclosure + dataString.toLocaleString() + defaults.csvEnclosure; else { result = preventInjection(csvValue); result = replaceAll(result, defaults.csvEnclosure, defaults.csvEnclosure + defaults.csvEnclosure); if (result.indexOf(defaults.csvSeparator) >= 0 || /[\r\n ]/g.test(result)) result = defaults.csvEnclosure + result + defaults.csvEnclosure; } } } return result; }; var CollectCsvData = function ($rows, rowselector, length) { $rows.each(function () { trData = ''; ForEachVisibleCell(this, rowselector, rowIndex, length + $rows.length, function (cell, row, col) { trData += csvString(cell, row, col) + (defaults.type === 'tsv' ? '\t' : defaults.csvSeparator); }); trData = $.trim(trData).substring(0, trData.length - 1); if (trData.length > 0) { if (csvData.length > 0) csvData += '\n'; csvData += trData; } rowIndex++; }); return $rows.length; }; rowlength += CollectCsvData($(el).find('thead').first().find(defaults.theadSelector), 'th,td', rowlength); findTableElements($(el), 'tbody').each(function () { rowlength += CollectCsvData(findTableElements($(this), defaults.tbodySelector), 'td,th', rowlength); }); if (defaults.tfootSelector.length) CollectCsvData($(el).find('tfoot').first().find(defaults.tfootSelector), 'td,th', rowlength); csvData += '\n'; //output if (defaults.outputMode === 'string') return csvData; if (defaults.outputMode === 'base64') return base64encode(csvData); if (defaults.outputMode === 'window') { downloadFile(false, 'data:text/' + (defaults.type === 'csv' ? 'csv' : 'plain') + ';charset=utf-8,', csvData); return; } saveToFile(csvData, defaults.fileName + '.' + defaults.type, 'text/' + (defaults.type === 'csv' ? 'csv' : 'plain'), 'utf-8', '', (defaults.type === 'csv' && defaults.csvUseBOM)); } else if (defaults.type === 'sql') { // Header rowIndex = 0; ranges = []; var tdData = 'INSERT INTO ' + defaults.sql.tableEnclosure + defaults.tableName + defaults.sql.tableEnclosure + ' ('; $hrows = collectHeadRows($(el)); $($hrows).each(function () { ForEachVisibleCell(this, 'th,td', rowIndex, $hrows.length, function (cell, row, col) { var colName = parseString(cell, row, col) || ''; if (colName.indexOf(defaults.sql.columnEnclosure) > -1) colName = replaceAll(colName.toString(), defaults.sql.columnEnclosure, defaults.sql.columnEnclosure + defaults.sql.columnEnclosure); tdData += defaults.sql.columnEnclosure + colName + defaults.sql.columnEnclosure + ','; }); rowIndex++; tdData = $.trim(tdData).substring(0, tdData.length - 1); }); tdData += ') VALUES '; // Data $rows = collectRows($(el)); $($rows).each(function () { trData = ''; ForEachVisibleCell(this, 'td,th', rowIndex, $hrows.length + $rows.length, function (cell, row, col) { var dataString = parseString(cell, row, col) || ''; if (dataString.indexOf('\'') > -1) dataString = replaceAll(dataString.toString(), '\'', '\'\''); trData += '\'' + dataString + '\','; }); if (trData.length > 3) { tdData += '(' + trData; tdData = $.trim(tdData).substring(0, tdData.length - 1); tdData += '),'; } rowIndex++; }); tdData = $.trim(tdData).substring(0, tdData.length - 1); tdData += ';'; // Output if (defaults.outputMode === 'string') return tdData; if (defaults.outputMode === 'base64') return base64encode(tdData); saveToFile(tdData, defaults.fileName + '.sql', 'application/sql', 'utf-8', '', false); } else if (defaults.type === 'json') { var jsonHeaderArray = []; ranges = []; $hrows = collectHeadRows($(el)); $($hrows).each(function () { var jsonArrayTd = []; ForEachVisibleCell(this, 'th,td', rowIndex, $hrows.length, function (cell, row, col) { jsonArrayTd.push(parseString(cell, row, col)); }); jsonHeaderArray.push(jsonArrayTd); }); // Data var jsonArray = []; $rows = collectRows($(el)); $($rows).each(function () { var jsonObjectTd = {}; var colIndex = 0; ForEachVisibleCell(this, 'td,th', rowIndex, $hrows.length + $rows.length, function (cell, row, col) { if (jsonHeaderArray.length) { jsonObjectTd[jsonHeaderArray[jsonHeaderArray.length - 1][colIndex]] = parseString(cell, row, col); } else { jsonObjectTd[colIndex] = parseString(cell, row, col); } colIndex++; }); if ($.isEmptyObject(jsonObjectTd) === false) jsonArray.push(jsonObjectTd); rowIndex++; }); var sdata = ''; if (defaults.jsonScope === 'head') sdata = JSON.stringify(jsonHeaderArray); else if (defaults.jsonScope === 'data') sdata = JSON.stringify(jsonArray); else // all sdata = JSON.stringify({header: jsonHeaderArray, data: jsonArray}); if (defaults.outputMode === 'string') return sdata; if (defaults.outputMode === 'base64') return base64encode(sdata); saveToFile(sdata, defaults.fileName + '.json', 'application/json', 'utf-8', 'base64', false); } else if (defaults.type === 'xml') { rowIndex = 0; ranges = []; var xml = '<?xml version="1.0" encoding="utf-8"?>'; xml += '<tabledata><fields>'; // Header $hrows = collectHeadRows($(el)); $($hrows).each(function () { ForEachVisibleCell(this, 'th,td', rowIndex, $hrows.length, function (cell, row, col) { xml += '<field>' + parseString(cell, row, col) + '</field>'; }); rowIndex++; }); xml += '</fields><data>'; // Data var rowCount = 1; $rows = collectRows($(el)); $($rows).each(function () { var colCount = 1; trData = ''; ForEachVisibleCell(this, 'td,th', rowIndex, $hrows.length + $rows.length, function (cell, row, col) { trData += '<column-' + colCount + '>' + parseString(cell, row, col) + '</column-' + colCount + '>'; colCount++; }); if (trData.length > 0 && trData !== '<column-1></column-1>') { xml += '<row id="' + rowCount + '">' + trData + '</row>'; rowCount++; } rowIndex++; }); xml += '</data></tabledata>'; // Output if (defaults.outputMode === 'string') return xml; if (defaults.outputMode === 'base64') return base64encode(xml); saveToFile(xml, defaults.fileName + '.xml', 'application/xml', 'utf-8', 'base64', false); } else if (defaults.type === 'excel' && defaults.mso.fileFormat === 'xmlss') { var docDatas = []; var docNames = []; $(el).filter(function () { return isVisible($(this)); }).each(function () { var $table = $(this); var ssName = ''; if (typeof defaults.mso.worksheetName === 'string' && defaults.mso.worksheetName.length) ssName = defaults.mso.worksheetName + ' ' + (docNames.length + 1); else if (typeof defaults.mso.worksheetName[docNames.length] !== 'undefined') ssName = defaults.mso.worksheetName[docNames.length]; if (!ssName.length) ssName = $table.find('caption').text() || ''; if (!ssName.length) ssName = 'Table ' + (docNames.length + 1); ssName = $.trim(ssName.replace(/[\\\/[\]*:?'"]/g, '').substring(0, 31)); docNames.push($('<div />').text(ssName).html()); if (defaults.exportHiddenCells === false) { $hiddenTableElements = $table.find('tr, th, td').filter(':hidden'); checkCellVisibilty = $hiddenTableElements.length > 0; } rowIndex = 0; colNames = GetColumnNames(this); docData = '<Table>\r'; function CollectXmlssData ($rows, rowselector, length) { var spans = []; $($rows).each(function () { var ssIndex = 0; var nCols = 0; trData = ''; ForEachVisibleCell(this, 'td,th', rowIndex, length + $rows.length, function (cell, row, col) { if (cell !== null) { var style = ''; var data = parseString(cell, row, col); var type = 'String'; if (jQuery.isNumeric(data) !== false) { type = 'Number'; } else { var number = parsePercent(data); if (number !== false) { data = number; type = 'Number'; style += ' ss:StyleID="pct1"'; } } if (type !== 'Number') data = data.replace(/\n/g, '<br>'); var colspan = getColspan(cell); var rowspan = getRowspan(cell); // Skip spans $.each(spans, function () { var range = this; if (rowIndex >= range.s.r && rowIndex <= range.e.r && nCols >= range.s.c && nCols <= range.e.c) { for (var i = 0; i <= range.e.c - range.s.c; ++i) { nCols++; ssIndex++; } } }); // Handle Row Span if (rowspan || colspan) { rowspan = rowspan || 1; colspan = colspan || 1; spans.push({ s: {r: rowIndex, c: nCols}, e: {r: rowIndex + rowspan - 1, c: nCols + colspan - 1} }); } // Handle Colspan if (colspan > 1) { style += ' ss:MergeAcross="' + (colspan - 1) + '"'; nCols += (colspan - 1); } if (rowspan > 1) { style += ' ss:MergeDown="' + (rowspan - 1) + '" ss:StyleID="rsp1"'; } if (ssIndex > 0) { style += ' ss:Index="' + (nCols + 1) + '"'; ssIndex = 0; } trData += '<Cell' + style + '><Data ss:Type="' + type + '">' + $('<div />').text(data).html() + '</Data></Cell>\r'; nCols++; } }); if (trData.length > 0) docData += '<Row ss:AutoFitHeight="0">\r' + trData + '</Row>\r'; rowIndex++; }); return $rows.length; } var rowLength = CollectXmlssData(collectHeadRows($table), 'th,td', 0); CollectXmlssData(collectRows($table), 'td,th', rowLength); docData += '</Table>\r'; docDatas.push(docData); }); var count = {}; var firstOccurences = {}; var item, itemCount; for (var n = 0, c = docNames.length; n < c; n++) { item = docNames[n]; itemCount = count[item]; itemCount = count[item] = (itemCount == null ? 1 : itemCount + 1); if (itemCount === 2) docNames[firstOccurences[item]] = docNames[firstOccurences[item]].substring(0, 29) + '-1'; if (count[item] > 1) docNames[n] = docNames[n].substring(0, 29) + '-' + count[item]; else firstOccurences[item] = n; } var CreationDate = new Date().toISOString(); var xmlssDocFile = '<?xml version="1.0" encoding="UTF-8"?>\r' + '<?mso-application progid="Excel.Sheet"?>\r' + '<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"\r' + ' xmlns:o="urn:schemas-microsoft-com:office:office"\r' + ' xmlns:x="urn:schemas-microsoft-com:office:excel"\r' + ' xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"\r' + ' xmlns:html="http://www.w3.org/TR/REC-html40">\r' + '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">\r' + ' <Created>' + CreationDate + '</Created>\r' + '</DocumentProperties>\r' + '<OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office">\r' + ' <AllowPNG/>\r' + '</OfficeDocumentSettings>\r' + '<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">\r' + ' <WindowHeight>9000</WindowHeight>\r' + ' <WindowWidth>13860</WindowWidth>\r' + ' <WindowTopX>0</WindowTopX>\r' + ' <WindowTopY>0</WindowTopY>\r' + ' <ProtectStructure>False</ProtectStructure>\r' + ' <ProtectWindows>False</ProtectWindows>\r' + '</ExcelWorkbook>\r' + '<Styles>\r' + ' <Style ss:ID="Default" ss:Name="Normal">\r' + ' <Alignment ss:Vertical="Bottom"/>\r' + ' <Borders/>\r' + ' <Font/>\r' + ' <Interior/>\r' + ' <NumberFormat/>\r' + ' <Protection/>\r' + ' </Style>\r' + ' <Style ss:ID="rsp1">\r' + ' <Alignment ss:Vertical="Center"/>\r' + ' </Style>\r' + ' <Style ss:ID="pct1">\r' + ' <NumberFormat ss:Format="Percent"/>\r' + ' </Style>\r' + '</Styles>\r'; for (var j = 0; j < docDatas.length; j++) { xmlssDocFile += '<Worksheet ss:Name="' + docNames[j] + '" ss:RightToLeft="' + (defaults.mso.rtl ? '1' : '0') + '">\r' + docDatas[j]; if (defaults.mso.rtl) { xmlssDocFile += '<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">\r' + '<DisplayRightToLeft/>\r' + '</WorksheetOptions>\r'; } else xmlssDocFile += '<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel"/>\r'; xmlssDocFile += '</Worksheet>\r'; } xmlssDocFile += '</Workbook>\r'; if (defaults.outputMode === 'string') return xmlssDocFile; if (defaults.outputMode === 'base64') return base64encode(xmlssDocFile); saveToFile(xmlssDocFile, defaults.fileName + '.xml', 'application/xml', 'utf-8', 'base64', false); } else if (defaults.type === 'excel' && defaults.mso.fileFormat === 'xlsx') { var sheetNames = []; var workbook = XLSX.utils.book_new(); // Multiple worksheets and .xlsx file extension #202 $(el).filter(function () { return isVisible($(this)); }).each(function () { var $table = $(this); var ws = xlsxTableToSheet(this); var sheetName = ''; if (typeof defaults.mso.worksheetName === 'string' && defaults.mso.worksheetName.length) sheetName = defaults.mso.worksheetName + ' ' + (sheetNames.length + 1); else if (typeof defaults.mso.worksheetName[sheetNames.length] !== 'undefined') sheetName = defaults.mso.worksheetName[sheetNames.length]; if (!sheetName.length) sheetName = $table.find('caption').text() || ''; if (!sheetName.length) sheetName = 'Table ' + (sheetNames.length + 1); sheetName = $.trim(sheetName.replace(/[\\\/[\]*:?'"]/g, '').substring(0, 31)); sheetNames.push(sheetName); XLSX.utils.book_append_sheet(workbook, ws, sheetName); }); // add worksheet to workbook var wbout = XLSX.write(workbook, {type: 'binary', bookType: defaults.mso.fileFormat, bookSST: false}); saveToFile(xlsxWorkbookToArrayBuffer(wbout), defaults.fileName + '.' + defaults.mso.fileFormat, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'UTF-8', '', false); } else if (defaults.type === 'excel' || defaults.type === 'xls' || defaults.type === 'word' || defaults.type === 'doc') { var MSDocType = (defaults.type === 'excel' || defaults.type === 'xls') ? 'excel' : 'word'; var MSDocExt = (MSDocType === 'excel') ? 'xls' : 'doc'; var MSDocSchema = 'xmlns:x="urn:schemas-microsoft-com:office:' + MSDocType + '"'; var docData = ''; var docName = ''; $(el).filter(function () { return isVisible($(this)); }).each(function () { var $table = $(this); if (docName === '') { docName = defaults.mso.worksheetName || $table.find('caption').text() || 'Table'; docName = $.trim(docName.replace(/[\\\/[\]*:?'"]/g, '').substring(0, 31)); } if (defaults.exportHiddenCells === false) { $hiddenTableElements = $table.find('tr, th, td').filter(':hidden'); checkCellVisibilty = $hiddenTableElements.length > 0; } rowIndex = 0; ranges = []; colNames = GetColumnNames(this); // Header docData += '<table><thead>'; $hrows = collectHeadRows($table); $($hrows).each(function () { var $row = $(this); trData = ''; ForEachVisibleCell(this, 'th,td', rowIndex, $hrows.length, function (cell, row, col) { if (cell !== null) { var thstyle = ''; trData += '<th'; if (defaults.mso.styles.length) { var cellstyles = document.defaultView.getComputedStyle(cell, null); var rowstyles = document.defaultView.getComputedStyle($row[0], null); for (var cssStyle in defaults.mso.styles) { var thcss = cellstyles[defaults.mso.styles[cssStyle]]; if (thcss === '') thcss = rowstyles[defaults.mso.styles[cssStyle]]; if (thcss !== '' && thcss !== '0px none rgb(0, 0, 0)' && thcss !== 'rgba(0, 0, 0, 0)') { thstyle += (thstyle === '') ? 'style="' : ';'; thstyle += defaults.mso.styles[cssStyle] + ':' + thcss; } } } if (thstyle !== '') trData += ' ' + thstyle + '"'; var tdcolspan = getColspan(cell); if (tdcolspan > 0) trData += ' colspan="' + tdcolspan + '"'; var tdrowspan = getRowspan(cell); if (tdrowspan > 0) trData += ' rowspan="' + tdrowspan + '"'; trData += '>' + parseString(cell, row, col) + '</th>'; } }); if (trData.length > 0) docData += '<tr>' + trData + '</tr>'; rowIndex++; }); docData += '</thead><tbody>'; // Data $rows = collectRows($table); $($rows).each(function () { var $row = $(this); trData = ''; ForEachVisibleCell(this, 'td,th', rowIndex, $hrows.length + $rows.length, function (cell, row, col) { if (cell !== null) { var tdvalue = parseString(cell, row, col); var tdstyle = ''; var tdcss = $(cell).attr('data-tableexport-msonumberformat'); if (typeof tdcss === 'undefined' && typeof defaults.mso.onMsoNumberFormat === 'function') tdcss = defaults.mso.onMsoNumberFormat(cell, row, col); if (typeof tdcss !== 'undefined' && tdcss !== '') tdstyle = 'style="mso-number-format:\'' + tdcss + '\''; if (defaults.mso.styles.length) { var cellstyles = document.defaultView.getComputedStyle(cell, null); var rowstyles = document.defaultView.getComputedStyle($row[0], null); for (var cssStyle in defaults.mso.styles) { tdcss = cellstyles[defaults.mso.styles[cssStyle]]; if (tdcss === '') tdcss = rowstyles[defaults.mso.styles[cssStyle]]; if (tdcss !== '' && tdcss !== '0px none rgb(0, 0, 0)' && tdcss !== 'rgba(0, 0, 0, 0)') { tdstyle += (tdstyle === '') ? 'style="' : ';'; tdstyle += defaults.mso.styles[cssStyle] + ':' + tdcss; } } } trData += '<td'; if (tdstyle !== '') trData += ' ' + tdstyle + '"'; var tdcolspan = getColspan(cell); if (tdcolspan > 0) trData += ' colspan="' + tdcolspan + '"'; var tdrowspan = getRowspan(cell); if (tdrowspan > 0) trData += ' rowspan="' + tdrowspan + '"'; if (typeof tdvalue === 'string' && tdvalue !== '') { tdvalue = preventInjection(tdvalue); tdvalue = tdvalue.replace(/\n/g, '<br>'); } trData += '>' + tdvalue + '</td>'; } }); if (trData.length > 0) docData += '<tr>' + trData + '</tr>'; rowIndex++; }); if (defaults.displayTableName) docData += '<tr><td></td></tr><tr><td></td></tr><tr><td>' + parseString($('<p>' + defaults.tableName + '</p>')) + '</td></tr>'; docData += '</tbody></table>'; }); //noinspection XmlUnusedNamespaceDeclaration var docFile = '<html xmlns:o="urn:schemas-microsoft-com:office:office" ' + MSDocSchema + ' xmlns="http://www.w3.org/TR/REC-html40">'; docFile += '<meta http-equiv="content-type" content="application/vnd.ms-' + MSDocType + '; charset=UTF-8">'; docFile += '<head>'; if (MSDocType === 'excel') { docFile += '<!--[if gte mso 9]>'; docFile += '<xml>'; docFile += '<x:ExcelWorkbook>'; docFile += '<x:ExcelWorksheets>'; docFile += '<x:ExcelWorksheet>'; docFile += '<x:Name>'; docFile += docName; docFile += '</x:Name>'; docFile += '<x:WorksheetOptions>'; docFile += '<x:DisplayGridlines/>'; if (defaults.mso.rtl) docFile += '<x:DisplayRightToLeft/>'; docFile += '</x:WorksheetOptions>'; docFile += '</x:ExcelWorksheet>'; docFile += '</x:ExcelWorksheets>'; docFile += '</x:ExcelWorkbook>'; docFile += '</xml>'; docFile += '<![endif]-->'; } docFile += '<style>'; docFile += '@page { size:' + defaults.mso.pageOrientation + '; mso-page-orientation:' + defaults.mso.pageOrientation + '; }'; docFile += '@page Section1 {size:' + pageFormats[defaults.mso.pageFormat][0] + 'pt ' + pageFormats[defaults.mso.pageFormat][1] + 'pt'; docFile += '; margin:1.0in 1.25in 1.0in 1.25in;mso-header-margin:.5in;mso-footer-margin:.5in;mso-paper-source:0;}'; docFile += 'div.Section1 {page:Section1;}'; docFile += '@page Section2 {size:' + pageFormats[defaults.mso.pageFormat][1] + 'pt ' + pageFormats[defaults.mso.pageFormat][0] + 'pt'; docFile += ';mso-page-orientation:' + defaults.mso.pageOrientation + ';margin:1.25in 1.0in 1.25in 1.0in;mso-header-margin:.5in;mso-footer-margin:.5in;mso-paper-source:0;}'; docFile += 'div.Section2 {page:Section2;}'; docFile += 'br {mso-data-placement:same-cell;}'; docFile += '</style>'; docFile += '</head>'; docFile += '<body>'; docFile += '<div class="Section' + ((defaults.mso.pageOrientation === 'landscape') ? '2' : '1') + '">'; docFile += docData; docFile += '</div>'; docFile += '</body>'; docFile += '</html>'; if (defaults.outputMode === 'string') return docFile; if (defaults.outputMode === 'base64') return base64encode(docFile); saveToFile(docFile, defaults.fileName + '.' + MSDocExt, 'application/vnd.ms-' + MSDocType, '', 'base64', false); } else if (defaults.type === 'png') { html2canvas($(el)[0]).then( function (canvas) { var image = canvas.toDataURL(); var byteString = atob(image.substring(22)); // remove data stuff var buffer = new ArrayBuffer(byteString.length); var intArray = new Uint8Array(buffer); for (var i = 0; i < byteString.length; i++) intArray[i] = byteString.charCodeAt(i); if (defaults.outputMode === 'string') return byteString; if (defaults.outputMode === 'base64') return base64encode(image); if (defaults.outputMode === 'window') { window.open(image); return; } saveToFile(buffer, defaults.fileName + '.png', 'image/png', '', '', false); }); } else if (defaults.type === 'pdf') { if (defaults.pdfmake.enabled === true) { // pdf output using pdfmake // https://github.com/bpampuch/pdfmake var widths = []; var body = []; rowIndex = 0; ranges = []; /** * @return {number} */ var CollectPdfmakeData = function ($rows, colselector, length) { var rlength = 0; $($rows).each(function () { var r = []; ForEachVisibleCell(this, colselector, rowIndex, length, function (cell, row, col) { if (typeof cell !== 'undefined' && cell !== null) { var colspan = getColspan(cell); var rowspan = getRowspan(cell); var cellValue = parseString(cell, row, col) || ' '; if (colspan > 1 || rowspan > 1) { colspan = colspan || 1; rowspan = rowspan || 1; r.push({colSpan: colspan, rowSpan: rowspan, text: cellValue}); } else r.push(cellValue); } else r.push(' '); }); if (r.length) body.push(r); if (rlength < r.length) rlength = r.length; rowIndex++; }); return rlength; }; $hrows = collectHeadRows($(this)); var colcount = CollectPdfmakeData($hrows, 'th,td', $hrows.length); for (var i = widths.length; i < colcount; i++) widths.push('*'); // Data $rows = collectRows($(this)); CollectPdfmakeData($rows, 'th,td', $hrows.length + $rows.length); var docDefinition = { content: [{ table: { headerRows: $hrows.length, widths: widths, body: body } }] }; $.extend(true, docDefinition, defaults.pdfmake.docDefinition); pdfMake.fonts = { Roboto: { normal: 'Roboto-Regular.ttf', bold: 'Roboto-Medium.ttf', italics: 'Roboto-Italic.ttf', bolditalics: 'Roboto-MediumItalic.ttf' } }; $.extend(true, pdfMake.fonts, defaults.pdfmake.fonts); pdfMake.createPdf(docDefinition).getBuffer(function (buffer) { saveToFile(buffer, defaults.fileName + '.pdf', 'application/pdf', '', '', false); }); } else if (defaults.jspdf.autotable === false) { // pdf output using jsPDF's core html support var addHtmlOptions = { dim: { w: getPropertyUnitValue($(el).first().get(0), 'width', 'mm'), h: getPropertyUnitValue($(el).first().get(0), 'height', 'mm') }, pagesplit: false }; var doc = new jsPDF(defaults.jspdf.orientation, defaults.jspdf.unit, defaults.jspdf.format); doc.addHTML($(el).first(), defaults.jspdf.margins.left, defaults.jspdf.margins.top, addHtmlOptions, function () { jsPdfOutput(doc, false); }); //delete doc; } else { // pdf output using jsPDF AutoTable plugin // https://github.com/simonbengtsson/jsPDF-AutoTable var teOptions = defaults.jspdf.autotable.tableExport; // When setting jspdf.format to 'bestfit' tableExport tries to choose // the minimum required paper format and orientation in which the table // (or tables in multitable mode) completely fits without column adjustment if (typeof defaults.jspdf.format === 'string' && defaults.jspdf.format.toLowerCase() === 'bestfit') { var rk = '', ro = ''; var mw = 0; $(el).each(function () { if (isVisible($(this))) { var w = getPropertyUnitValue($(this).get(0), 'width', 'pt'); if (w > mw) { if (w > pageFormats.a0[0]) { rk = 'a0'; ro = 'l'; } for (var key in pageFormats) { if (pageFormats.hasOwnProperty(key)) { if (pageFormats[key][1] > w) { rk = key; ro = 'l'; if (pageFormats[key][0] > w) ro = 'p'; } } } mw = w; } } }); defaults.jspdf.format = (rk === '' ? 'a4' : rk); defaults.jspdf.orientation = (ro === '' ? 'w' : ro); } // The jsPDF doc object is stored in defaults.jspdf.autotable.tableExport, // thus it can be accessed from any callback function if (teOptions.doc == null) { teOptions.doc = new jsPDF(defaults.jspdf.orientation, defaults.jspdf.unit, defaults.jspdf.format); teOptions.wScaleFactor = 1; teOptions.hScaleFactor = 1; if (typeof defaults.jspdf.onDocCreated === 'function') defaults.jspdf.onDocCreated(teOptions.doc); } if (teOptions.outputImages === true) teOptions.images = {}; if (typeof teOptions.images !== 'undefined') { $(el).filter(function () { return isVisible($(this)); }).each(function () { var rowCount = 0; ranges = []; if (defaults.exportHiddenCells === false) { $hiddenTableElements = $(this).find('tr, th, td').filter(':hidden'); checkCellVisibilty = $hiddenTableElements.length > 0; } $hrows = collectHeadRows($(this)); $rows = collectRows($(this)); $($rows).each(function () { ForEachVisibleCell(this, 'td,th', $hrows.length + rowCount, $hrows.length + $rows.length, function (cell) { collectImages(cell, $(cell).children(), teOptions); }); rowCount++; }); }); $hrows = []; $rows = []; } loadImages(teOptions, function () { $(el).filter(function () { return isVisible($(this)); }).each(function () { var colKey; rowIndex = 0; ranges = []; if (defaults.exportHiddenCells === false) { $hiddenTableElements = $(this).find('tr, th, td').filter(':hidden'); checkCellVisibilty = $hiddenTableElements.length > 0; } colNames = GetColumnNames(this); teOptions.columns = []; teOptions.rows = []; teOptions.teCells = {}; // onTable: optional callback function for every matching table that can be used // to modify the tableExport options or to skip the output of a particular table // if the table selector targets multiple tables if (typeof teOptions.onTable === 'function') if (teOptions.onTable($(this), defaults) === false) return true; // continue to next iteration step (table) // each table works with an own copy of AutoTable options defaults.jspdf.autotable.tableExport = null; // avoid deep recursion error var atOptions = $.extend(true, {}, defaults.jspdf.autotable); defaults.jspdf.autotable.tableExport = teOptions; atOptions.margin = {}; $.extend(true, atOptions.margin, defaults.jspdf.margins); atOptions.tableExport = teOptions; // Fix jsPDF Autotable's row height calculation if (typeof atOptions.beforePageContent !== 'function') { atOptions.beforePageContent = function (data) { if (data.pageCount === 1) { var all = data.table.rows.concat(data.table.headerRow); $.each(all, function () { var row = this; if (row.height > 0) { row.height += (2 - FONT_ROW_RATIO) / 2 * row.styles.fontSize; data.table.height += (2 - FONT_ROW_RATIO) / 2 * row.styles.fontSize; } }); } }; } if (typeof atOptions.createdHeaderCell !== 'function') { // apply some original css styles to pdf header cells atOptions.createdHeaderCell = function (cell, data) { // jsPDF AutoTable plugin v2.0.14 fix: each cell needs its own styles object cell.styles = $.extend({}, data.row.styles); if (typeof teOptions.columns [data.column.dataKey] !== 'undefined') { var col = teOptions.columns [data.column.dataKey]; if (typeof col.rect !== 'undefined') { var rh; cell.contentWidth = col.rect.width; if (typeof teOptions.heightRatio === 'undefined' || teOptions.heightRatio === 0) { if (data.row.raw [data.column.dataKey].rowspan) rh = data.row.raw [data.column.dataKey].rect.height / data.row.raw [data.column.dataKey].rowspan; else rh = data.row.raw [data.column.dataKey].rect.height; teOptions.heightRatio = cell.styles.rowHeight / rh; } rh = data.row.raw [data.column.dataKey].rect.height * teOptions.heightRatio; if (rh > cell.styles.rowHeight) cell.styles.rowHeight = rh; } cell.styles.halign = (atOptions.headerStyles.halign === 'inherit') ? 'center' : atOptions.headerStyles.halign; cell.styles.valign = atOptions.headerStyles.valign; if (typeof col.style !== 'undefined' && col.style.hidden !== true) { if (atOptions.headerStyles.halign === 'inherit') cell.styles.halign = col.style.align; if (atOptions.styles.fillColor === 'inherit') cell.styles.fillColor = col.style.bcolor; if (atOptions.styles.textColor === 'inherit') cell.styles.textColor = col.style.color; if (atOptions.styles.fontStyle === 'inherit') cell.styles.fontStyle = col.style.fstyle; } } }; } if (typeof atOptions.createdCell !== 'function') { // apply some original css styles to pdf table cells atOptions.createdCell = function (cell, data) { var tecell = teOptions.teCells [data.row.index + ':' + data.column.dataKey]; cell.styles.halign = (atOptions.styles.halign === 'inherit') ? 'center' : atOptions.styles.halign; cell.styles.valign = atOptions.styles.valign; if (typeof tecell !== 'undefined' && typeof