【js-xlsx和file-saver插件】前端html的table导出数据到excel的表格增加表格标题行
基于上一篇随笔后,新需求需要再导出的表格上面加一行标题行
1 function parse_dom_table_addtitle(table, _opts, title) { 2 var opts = _opts || {}; 3 var oss = opts.defaultCellStyle || {}; /*单元格样式 */ 4 if (DENSE != null) opts.dense = DENSE; 5 var ws = opts.dense ? ([]) : ({}); 6 var rows = table.getElementsByTagName('tr'); 7 var sheetRows = Math.min(opts.sheetRows || 10000000, rows.length); 8 var range = { s: { r: 0, c: 0 }, e: { r: sheetRows+1 , c: 0 } }; 9 var merges = [], midx = 0; 10 var R = 1, _C = 0, C = 0, RS = 0, CS = 0; 11 var _title = title || ""; 12 var title_o = { t: 's', v: _title, s: oss }; 13 ws[encode_cell({ c: 0, r: 0 })] = title_o; 14 var maxc = 0; 15 for (; R < sheetRows+1; ++R) { 16 var nR = R - 1 17 var row = rows[nR]; 18 var elts = (row.children); 19 for (_C = C = 0; _C < elts.length; ++_C) { 20 var elt = elts[_C], v = htmldecode(elts[_C].innerHTML); 21 for (midx = 0; midx < merges.length; ++midx) { 22 var m = merges[midx]; 23 if (m.s.c == C && m.s.r <= R && R <= m.e.r) { 24 C = m.e.c + 1; midx = -1; 25 } 26 } 27 /* TODO: figure out how to extract nonstandard mso- style */ 28 CS = +elt.getAttribute("colspan") || 1; 29 if ((RS = +elt.getAttribute("rowspan")) > 0 || CS > 1) 30 merges.push({ s: { r: R, c: C }, e: { r: R + (RS || 1) - 1, c: C + CS - 1 } }); 31 var o = { t: 's', v: v, s: oss }; 32 var _t = elt.getAttribute("t") || ""; 33 if (v != null) { 34 if (v.length == 0) o.t = _t || 's'; 35 else if (opts.raw || v.trim().length == 0 || _t == "s") { } 36 else if (v === 'TRUE') o = { t: 'b', v: true, s: oss }; 37 else if (v === 'FALSE') o = { t: 'b', v: false, s: oss }; 38 else if (!isNaN(fuzzynum(v))) o = { t: 'n', v: fuzzynum(v), s: oss }; 39 else if (!isNaN(fuzzydate(v).getDate())) { 40 o = ({ t: 'd', v: parseDate(v), s: oss }); 41 if (!opts.cellDates) o = ({ t: 'n', v: datenum(o.v), s: oss }); 42 o.z = opts.dateNF || SSF._table[14]; 43 } 44 } 45 if (opts.dense) { if (!ws[R]) ws[R] = []; ws[R][C] = o; } 46 else ws[encode_cell({ c: C, r: R })] = o; 47 /* 合并数据处理开始*/ 48 if (CS > 1) { 49 for (var i = 1; i < CS; i++) { 50 var newc = C + i 51 if (RS > 1) { 52 for (var m = 1; m < RS; m++) { 53 var newr = R + m; 54 ws[encode_cell({ c: newc, r: newr })] = o; 55 } 56 } 57 else { 58 ws[encode_cell({ c: newc, r: R })] = o; 59 } 60 } 61 } 62 else { 63 if (RS > 1) { 64 for (var m = 1; m < RS; m++) { 65 var newr = R + m; 66 ws[encode_cell({ c: C, r: newr })] = o; 67 } 68 } 69 else { 70 ws[encode_cell({ c: C, r: R })] = o; 71 } 72 } 73 /*合并数据处理结束*/ 74 if (range.e.c < C) range.e.c = C; 75 C += CS; 76 if (maxc < C) 77 { 78 maxc = C; 79 } 80 } 81 if (R == sheetRows) 82 { 83 merges.push({ s: { r: 0, c: 0 }, e: { r: 0, c: maxc-1 } }); 84 } 85 } 86 ws['!merges'] = merges; 87 ws['!ref'] = encode_range(range); 88 if (sheetRows < rows.length) ws['!fullref'] = encode_range((range.e.r = rows.length-1 , range)); 89 return ws; 90 }