forked from hhurz/tableExport.jquery.plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tableExport.js
2376 lines (2020 loc) · 92.7 KB
/
tableExport.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @preserve tableExport.jquery.plugin
*
* Version 1.10.2
*
* Copyright (c) 2015-2018 hhurz, https://github.com/hhurz
*
* Original Work Copyright (c) 2014 Giri Raj
*
* Licensed under the MIT License
**/
'use strict';
(function ($) {
$.fn.tableExport = function (options) {
var defaults = {
csvEnclosure: '"',
csvSeparator: ',',
csvUseBOM: true,
displayTableName: false,
escape: false,
exportHiddenCells: false, // true = speed up export of large tables with hidden cells (hidden cells will be exported !)
fileName: 'tableExport',
htmlContent: false,
ignoreColumn: [],
ignoreRow: [],
jsonScope: 'all', // head, data, all
jspdf: { // jsPDF / jsPDF-AutoTable related options
orientation: 'p',
unit: 'pt',
format: 'a4', // One of jsPDF page formats or 'bestfit' for autmatic 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 fonst-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, 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, bottom
},
alternateRowStyles: {
fillColor: 245
},
tableExport: {
doc: null, // jsPDF doc object. If set, an already created doc 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: ''
},
numbers: {
html: {
decimalMark: '.',
thousandsSeparator: ','
},
output: { // Use 'output: false' to keep number format in exported output
decimalMark: '.',
thousandsSeparator: ','
}
},
onCellData: null,
onCellHtmlData: null,
onIgnoreRow: null, // onIgnoreRow($tr, rowIndex): function should return true to not export a 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 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,
tbodySelector: 'tr',
tfootSelector: 'tr', // Set empty ('') to prevent export of tfoot rows
theadSelector: 'tr',
tableName: 'Table',
type: 'csv' // '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';
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;
}
try {
blob = new Blob([csvData], {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);
}
} else if ( defaults.type === 'sql' ) {
// Header
rowIndex = 0;
ranges = [];
var tdData = "INSERT INTO `" + defaults.tableName + "` (";
$hrows = collectHeadRows ($(el));
$($hrows).each(function () {
ForEachVisibleCell(this, 'th,td', rowIndex, $hrows.length,
function (cell, row, col) {
tdData += "'" + parseString(cell, row, col) + "',";
});
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) {
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.outputMode === 'string' )
return tdData;
if ( defaults.outputMode === 'base64' )
return base64encode(tdData);
try {
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 = [];
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);
try {
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;
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);
try {
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.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', rowLength);
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);
try {
blob = new Blob([xmlssDocFile], {type: "application/xml;charset=utf-8"});
saveAs(blob, defaults.fileName + '.xml');
}
catch (e) {
downloadFile(defaults.fileName + '.xml',
'data:application/xml;charset=utf-8;base64,',
xmlssDocFile);
}
}
else if ( defaults.type === 'excel' && defaults.mso.fileFormat === 'xlsx' ) {
var data = [];
var spans = [];
rowIndex = 0;
$rows = collectHeadRows ($(el));
$rows.push.apply($rows, collectRows ($(el)));
$($rows).each(function () {
var cols = [];
ForEachVisibleCell(this, 'th,td', rowIndex, $rows.length,
function (cell, row, col) {
if ( typeof cell !== 'undefined' && cell !== null ) {
var cellValue = parseString(cell, row, col);
var colspan = getColspan (cell);
var rowspan = getRowspan (cell);
// Skip span ranges
$.each(spans, function () {
var range = this;
if ( rowIndex >= range.s.r && rowIndex <= range.e.r && cols.length >= range.s.c && cols.length <= range.e.c ) {
for ( var i = 0; i <= range.e.c - range.s.c; ++i )
cols.push(null);
}
});
// Handle Row Span
if ( rowspan || colspan ) {
rowspan = rowspan || 1;
colspan = colspan || 1;
spans.push({
s: {r: rowIndex, c: cols.length},
e: {r: rowIndex + rowspan - 1, c: cols.length + colspan - 1}
});
}
// Handle Value
if ( typeof defaults.onCellData !== 'function' ) {
// Type conversion
if ( cellValue !== "" && cellValue === +cellValue )
cellValue = +cellValue;
}
cols.push(cellValue !== "" ? cellValue : null);
// Handle Colspan
if ( colspan )
for ( var k = 0; k < colspan - 1; ++k )
cols.push(null);
}
});
data.push(cols);
rowIndex++;
});
//noinspection JSPotentiallyInvalidConstructorUsage
var wb = new jx_Workbook(),
ws = jx_createSheet(data);
// add span ranges to worksheet
ws['!merges'] = spans;
// add worksheet to workbook
//wb.SheetNames.push(defaults.mso.worksheetName);
//wb.Sheets[defaults.mso.worksheetName] = ws;
XLSX.utils.book_append_sheet(wb, ws, defaults.mso.worksheetName);
var wbout = XLSX.write(wb, {type: 'binary', bookType: defaults.mso.fileFormat, bookSST: false});
try {
blob = new Blob([jx_s2ab(wbout)], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'});
saveAs(blob, defaults.fileName + '.' + defaults.mso.fileFormat);
}
catch (e) {
downloadFile(defaults.fileName + '.' + defaults.mso.fileFormat,
'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8,',
jx_s2ab(wbout));
}
}
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 () {
trData = "";
ForEachVisibleCell(this, 'th,td', rowIndex, $hrows.length,
function (cell, row, col) {
if ( cell !== null ) {
var thstyle = '';
trData += '<th';
for ( var styles in defaults.mso.styles ) {
if ( defaults.mso.styles.hasOwnProperty(styles) ) {
var thcss = $(cell).css(defaults.mso.styles[styles]);
if ( thcss !== '' && thcss !== '0px none rgb(0, 0, 0)' && thcss !== 'rgba(0, 0, 0, 0)' ) {
thstyle += (thstyle === '') ? 'style="' : ';';
thstyle += defaults.mso.styles[styles] + ':' + 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).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 + '\'';
for ( var cssStyle in defaults.mso.styles ) {
if ( defaults.mso.styles.hasOwnProperty(cssStyle) ) {
tdcss = $(cell).css(defaults.mso.styles[cssStyle]);
if ( tdcss === '' )
tdcss = $row.css(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);
try {
blob = new Blob([docFile], {type: 'application/vnd.ms-' + defaults.type});
saveAs(blob, defaults.fileName + '.' + MSDocExt);
}
catch (e) {
downloadFile(defaults.fileName + '.' + MSDocExt,
'data:application/vnd.ms-' + MSDocType + ';base64,',
docFile);
}
}
else if ( defaults.type === 'png' ) {
//html2canvas($(el)[0], {
// onrendered: function (canvas) {
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;
}
try {
blob = new Blob([buffer], {type: "image/png"});
saveAs(blob, defaults.fileName + '.png');
}
catch (e) {
downloadFile(defaults.fileName + '.png', 'data:image/png,', blob);
}
//}
});
} 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;