最近项目要js实现将数据导出excel文件,网上很多插件实现~~那个开心呀,谁知道后面数据量达到上万条时出问题:浏览器不仅卡死,导出的excel文件一直提示网络失败。。。。
debug调试发现var excel拼接的table字符串,超出了var的长度限制;幸好网上有前辈的解决方案~~~膜拜ing
参考网址:
栗子: html页面:
js Blod 保存文件 ===========================================js Blod 保存文件========================================
====================================tableExport.jquery.plugin.js====================================
编号 名单 组ID 组名 类型 更新时间 更新者 编号1 白名单1 组ID1 组名1 类型1 更新时间1 更新者1 编号2 名单2 组ID2 组名2 类型2 更新时间2 更新者2
tableExport.jquery.plugin.js
/* tableExport.jquery.plugin Copyright (c) 2015 hhurz, c Original work Copyright (c) 2014 Giri Raj, https://github.com/kayalshri/ Licensed under the MIT License, http://opensource.org/licenses/mit-license*/(function ($) { $.fn.extend({ tableExport: function (options) { var defaults = { consoleLog: false, csvEnclosure: '"', csvSeparator: ',', csvUseBOM: true, displayTableName: false, escape: false, excelstyles: ['border-bottom', 'border-top', 'border-left', 'border-right'], fileName: 'tableExport', htmlContent: false, ignoreColumn: [], ignoreRow:[], jspdf: {orientation: 'p', unit: 'pt', format: 'a4', // jspdf page format or 'bestfit' for autmatic paper format selection margins: {left: 20, right: 10, top: 10, bottom: 10}, 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 fonst-style from html table overflow: 'ellipsize', // visible, hidden, ellipsize or linebreak halign: 'left', // left, center, right valign: 'middle' // top, middle, bottom }, headerStyles: {fillColor: [52, 73, 94], textColor: 255, fontStyle: 'bold', halign: 'center' }, alternateRowStyles: {fillColor: 245 }, tableExport: {onAfterAutotable: null, onBeforeAutotable: null, onTable: null } } }, numbers: {html: {decimalMark: '.', thousandsSeparator: ',' }, output: {decimalMark: '.', thousandsSeparator: ',' } }, onCellData: null, onCellHtmlData: null, outputMode: 'file', // 'file', 'string' or 'base64' tbodySelector: 'tr', theadSelector: 'tr', tableName: 'myTableName', type: 'csv', // 'csv', 'txt', 'sql', 'json', 'xml', 'excel', 'doc', 'png' or 'pdf' worksheetName: 'xlsWorksheetName' }; var FONT_ROW_RATIO = 1.15; var el = this; var DownloadEvt = null; var $hrows = []; var $rows = []; var rowIndex = 0; var rowspans = []; var trData = ''; function StringBuffer() { this.content = new Array; } StringBuffer.prototype.append = function(str) { this.content.push(str); } StringBuffer.prototype.prepend = function(str) { this.content.unshift(str); } StringBuffer.prototype.toString = function() { return this.content.join(""); } $.extend(true, defaults, options); debugger if (defaults.type == 'csv' || defaults.type == 'txt') { var csvData = new StringBuffer(); var rowlength = 0; rowIndex = 0; function CollectCsvData (tgroup, tselector, rowselector, length) { $rows = $(el).find(tgroup).first().find(tselector); $rows.each(function () { csvData.append(this.innerHTML); rowIndex++; }); return $rows.length; } rowlength += CollectCsvData ('thead', defaults.theadSelector, 'th,td', rowlength); rowlength += CollectCsvData ('tbody', defaults.tbodySelector, 'td', rowlength); CollectCsvData ('tfoot', defaults.tbodySelector, 'td', rowlength); csvData.append("\n"); //output if (defaults.consoleLog === true) console.log(csvData); if (defaults.outputMode === 'string') return csvData; if (defaults.outputMode === 'base64') return base64encode(csvData); try { var blob = new Blob(csvData.content.slice(0,1200), {type: "text/" + (defaults.type == 'csv' ? 'csv' : 'plain') + ";charset=utf-8"}); saveAs(blob, defaults.fileName + '.' + defaults.type, (defaults.type != 'csv' || defaults.csvUseBOM === false)); } catch (e) { downloadFile(defaults.fileName + '.' + defaults.type, 'data:text/' + (defaults.type == 'csv' ? 'csv' : 'plain') + ';charset=utf-8,' + ((defaults.type == 'csv' && defaults.csvUseBOM)? '\ufeff' : ''), csvData.toString()); } } else if (defaults.type == 'sql') { // Header rowIndex = 0; var tdData = "INSERT INTO `" + defaults.tableName + "` ("; $hrows = $(el).find('thead').first().find(defaults.theadSelector); $hrows.each(function () { ForEachVisibleCell(this, 'th,td', rowIndex, $hrows.length, function (cell, row, col) { tdData += "'" + parseString(cell, row, col) + "',"; }); rowIndex++; tdData = $.trim(tdData); tdData = $.trim(tdData).substring(0, tdData.length - 1); }); tdData += ") VALUES "; // Row vs Column $rows = $(el).find('tbody').first().find(defaults.tbodySelector); $rows.each(function () { trData = ""; ForEachVisibleCell(this, 'td', rowIndex, $hrows.length + $rows.length, function (cell, row, col) { trData += "'" + parseString(cell, row, col) + "',"; }); 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.consoleLog === true) console.log(tdData); if (defaults.outputMode === 'string') return tdData; if (defaults.outputMode === 'base64') return base64encode(tdData); try { var blob = new Blob([tdData], {type: "text/plain;charset=utf-8"}); saveAs(blob, defaults.fileName + '.sql'); } catch (e) { downloadFile(defaults.fileName + '.sql', 'data:application/sql;charset=utf-8,', tdData); } } else if (defaults.type == 'json') { var jsonHeaderArray = []; $hrows = $(el).find('thead').first().find(defaults.theadSelector); $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); }); var jsonArray = []; $rows = $(el).find('tbody').first().find(defaults.tbodySelector); $rows.each(function () { var jsonArrayTd = []; ForEachVisibleCell(this, 'td', rowIndex, $hrows.length + $rows.length, function (cell, row, col) { jsonArrayTd.push(parseString(cell, row, col)); }); if (jsonArrayTd.length > 0 && (jsonArrayTd.length != 1 || jsonArrayTd[0] != "")) jsonArray.push(jsonArrayTd); rowIndex++; }); var jsonExportArray = []; jsonExportArray.push({header: jsonHeaderArray, data: jsonArray}); var sdata = JSON.stringify(jsonExportArray); if (defaults.consoleLog === true) console.log(sdata); if (defaults.outputMode === 'string') return sdata; if (defaults.outputMode === 'base64') return base64encode(sdata); try { var blob = new Blob([sdata], {type: "application/json;charset=utf-8"}); saveAs(blob, defaults.fileName + '.json'); } catch (e) { downloadFile(defaults.fileName + '.json', 'data:application/json;charset=utf-8;base64,', sdata); } } else if (defaults.type === 'xml') { rowIndex = 0; var xml = ' '; xml += ''; //output if (defaults.consoleLog === true) console.log(xml); if (defaults.outputMode === 'string') return xml; if (defaults.outputMode === 'base64') return base64encode(xml); try { var blob = new Blob([xml], {type: "application/xml;charset=utf-8"}); saveAs(blob, defaults.fileName + '.xml'); } catch (e) { downloadFile(defaults.fileName + '.xml', 'data:application/xml;charset=utf-8;base64,', xml); } } 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 = (MSDocExt == 'xls') ? 'xmlns:x="urn:schemas-microsoft-com:office:excel"' : 'xmlns:w="urn:schemas-microsoft-com:office:word"'; rowIndex = 0; var docData = new StringBuffer(); docData.append(' '; // Header $hrows = $(el).find('thead').first().find(defaults.theadSelector); $hrows.each(function () { ForEachVisibleCell(this, 'th,td', rowIndex, $rows.length, function (cell, row, col) { xml += " '; // Row Vs Column var rowCount = 1; $rows = $(el).find('tbody').first().find(defaults.tbodySelector); $rows.each(function () { var colCount = 1; trData = ""; ForEachVisibleCell(this, 'td', rowIndex, $hrows.length + $rows.length, function (cell, row, col) { trData += "" + parseString(cell, row, col) + " "; }); rowIndex++; }); xml += '" + parseString(cell, row, col) + " "; colCount++; }); if (trData.length > 0 && trData != "") { xml += ' ' + trData + '
'; rowCount++; } rowIndex++; }); xml += '
' + parseString($(' ' + defaults.tableName + ' ')) + ' |
/gi, '\u2060'); var obj = $(' ').html(text).contents(); text = ''; $.each(obj.text().split("\u2028"), function(i, v) { if (i > 0) text += " "; text += $.trim(v); }); $.each(text.split("\u2060"), function(i, v) { if (i > 0) result += "\n"; result += $.trim(v).replace(/\u00AD/g, ""); // remove soft hyphens }); if (defaults.numbers.html.decimalMark != defaults.numbers.output.decimalMark || defaults.numbers.html.thousandsSeparator != defaults.numbers.output.thousandsSeparator) { var number = parseNumber (result); if ( number !== false ) { var frac = ("" + number).split('.'); if ( frac.length == 1 ) frac[1] = ""; var mod = frac[0].length > 3 ? frac[0].length % 3 : 0; result = (number < 0 ? "-" : "") + (defaults.numbers.output.thousandsSeparator ? ((mod ? frac[0].substr(0, mod) + defaults.numbers.output.thousandsSeparator : "") + frac[0].substr(mod).replace(/(\d{3})(?=\d)/g, "$1" + defaults.numbers.output.thousandsSeparator)) : frac[0]) + (frac[1].length ? defaults.numbers.output.decimalMark + frac[1] : ""); } } } if (defaults.escape === true) { result = escape(result); } if (typeof defaults.onCellData === 'function') { result = defaults.onCellData($cell, rowIndex, colIndex, result); } } return result; } function hyphenate(a, b, c) { return b + "-" + c.toLowerCase(); } function rgb2array(rgb_string, default_result) { var re = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/; var bits = re.exec(rgb_string); var result = default_result; if (bits) result = [ parseInt(bits[1]), parseInt(bits[2]), parseInt(bits[3]) ]; return result; } function getCellStyles (cell) { var a = getStyle(cell, 'text-align'); var fw = getStyle(cell, 'font-weight'); var fs = getStyle(cell, 'font-style'); var f = ''; if (a == 'start') a = getStyle(cell, 'direction') == 'rtl' ? 'right' : 'left'; if (fw >= 700) f = 'bold'; if (fs == 'italic') f += fs; if (f == '') f = 'normal'; return { style: { align: a, bcolor: rgb2array(getStyle(cell, 'background-color'), [255, 255, 255]), color: rgb2array(getStyle(cell, 'color'), [0, 0, 0]), fstyle: f }, colspan: (parseInt($(cell).attr('colspan')) || 0), rowspan: (parseInt($(cell).attr('rowspan')) || 0) }; } // get computed style property function getStyle(target, prop) { try { if (window.getComputedStyle) { // gecko and webkit prop = prop.replace(/([a-z])([A-Z])/, hyphenate); // requires hyphenated, not camel return window.getComputedStyle(target, null).getPropertyValue(prop); } if (target.currentStyle) { // ie return target.currentStyle[prop]; } return target.style[prop]; } catch (e) { } return ""; } function getPropertyUnitValue(target, prop, unit) { var baseline = 100; // any number serves var value = getStyle(target, prop); // get the computed style value var numeric = value.match(/\d+/); // get the numeric component if (numeric !== null) { numeric = numeric[0]; // get the string var temp = document.createElement("div"); // create temporary element temp.style.overflow = "hidden"; // in case baseline is set too low temp.style.visibility = "hidden"; // no need to show it target.parentElement.appendChild(temp); // insert it into the parent for em, ex and % temp.style.width = baseline + unit; var factor = baseline / temp.offsetWidth; target.parentElement.removeChild(temp); // clean up return (numeric * factor); } return 0; } function downloadFile(filename, header, data) { var ua = window.navigator.userAgent; if (ua.indexOf("MSIE ") > 0 || !!ua.match(/Trident.*rv\:11\./)) { // Internet Explorer (<= 9) workaround by Darryl (https://github.com/dawiong/tableExport.jquery.plugin) // based on sampopes answer on http://stackoverflow.com/questions/22317951 // ! Not working for json and pdf format ! var frame = document.createElement("iframe"); if (frame) { document.body.appendChild(frame); frame.setAttribute("style", "display:none"); frame.contentDocument.open("txt/html", "replace"); frame.contentDocument.write(data); frame.contentDocument.close(); frame.focus(); frame.contentDocument.execCommand("SaveAs", true, filename); document.body.removeChild(frame); } } else { var DownloadLink = document.createElement('a'); if (DownloadLink) { DownloadLink.style.display = 'none'; DownloadLink.download = filename; console.log((header + base64encode(data)).length); if (header.toLowerCase().indexOf("base64,") >= 0) DownloadLink.href = header + base64encode(data); else DownloadLink.href = encodeURIComponent(header + data); document.body.appendChild(DownloadLink); if (document.createEvent) { if (DownloadEvt == null) DownloadEvt = document.createEvent('MouseEvents'); DownloadEvt.initEvent('click', true, false); DownloadLink.dispatchEvent(DownloadEvt); } else if (document.createEventObject) DownloadLink.fireEvent('onclick'); else if (typeof DownloadLink.onclick == 'function') DownloadLink.onclick(); /*document.body.removeChild(DownloadLink);*/ } } } function utf8Encode(string) { string = string.replace(/\x0d\x0a/g, "\x0a"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if ((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; } function saveAs(blob, filename) { var type = blob.type; var force_saveable_type = 'application/octet-stream'; if (type && type != force_saveable_type) { // 强制下载,而非在浏览器中打开 var slice = blob.slice || blob.webkitSlice || blob.mozSlice; blob = slice.call(blob, 0, blob.size, force_saveable_type); } var url = URL.createObjectURL(blob); var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a'); save_link.href = url; save_link.download = filename; var event = document.createEvent('MouseEvents'); event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); save_link.dispatchEvent(event); URL.revokeObjectURL(url); } function base64encode(input) { var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = utf8Encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); } return output; } return this; } });})(jQuery);