-
Notifications
You must be signed in to change notification settings - Fork 146
/
Copy pathindex.js
executable file
·1871 lines (1678 loc) · 83.3 KB
/
index.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
/*jshint globalstrict:true, devel:true */
/*eslint no-var:0 */
/*global require, module, Buffer */
/// <reference path="augment.d.ts" />
var path = require('path'),
sizeOf = require('image-size').imageSize,
fs = require('fs'),
etree = require('elementtree'),
zip = require("@kant2002/jszip");
var DOCUMENT_RELATIONSHIP = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
CALC_CHAIN_RELATIONSHIP = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/calcChain",
SHARED_STRINGS_RELATIONSHIP = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings",
HYPERLINK_RELATIONSHIP = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink";
var _get_simple = function (obj, desc) {
if (desc.indexOf("[") >=0 ) {
var specification = desc.split(/[[[\]]/);
var property = specification[0];
var index = specification[1];
return obj[property][index];
}
return obj[desc];
}
/**
* Based on http://stackoverflow.com/questions/8051975
* Mimic https://lodash.com/docs#get
*/
var _get = function(obj, desc, defaultValue) {
var arr = desc.split('.');
try {
while (arr.length) {
obj = _get_simple(obj, arr.shift());
}
} catch(ex) {
/* invalid chain */
obj = undefined;
}
return obj === undefined ? defaultValue : obj;
}
class Workbook {
/**
* Create a new workbook. Either pass the raw data of a .xlsx file,
* or call `loadTemplate()` later.
*/
constructor(data, option = {}) {
this.archive = null;
this.sharedStrings = [];
this.sharedStringsLookup = {};
this.option = {
moveImages: false,
subsituteAllTableRow: false,
moveSameLineImages: false,
imageRatio: 100,
pushDownPageBreakOnTableSubstitution: false,
imageRootPath: null,
handleImageError: null,
};
Object.assign(this.option, option);
this.sharedStringsPath = "";
this.sheets = [];
this.sheet = null;
this.workbook = null;
this.workbookPath = null;
this.contentTypes = null;
this.prefix = null;
this.workbookRels = null;
this.calChainRel = null;
this.calcChainPath = "";
if (data) {
this.loadTemplate(data);
}
}
/**
* Delete unused sheets if needed
*/
deleteSheet(sheetName) {
var self = this;
var sheet = self.loadSheet(sheetName);
var sh = self.workbook.find("sheets/sheet[@sheetId='" + sheet.id + "']");
self.workbook.find("sheets").remove(sh);
var rel = self.workbookRels.find("Relationship[@Id='" + sh.attrib['r:id'] + "']");
self.workbookRels.remove(rel);
self._rebuild();
return self;
}
/**
* Clone sheets in current workbook template
*/
copySheet(sheetName, copyName, binary = true) {
var self = this;
var sheet = self.loadSheet(sheetName); //filename, name , id, root
var newSheetIndex = (self.workbook.findall("sheets/sheet").length + 1).toString();
var fileName = 'worksheets' + '/' + 'sheet' + newSheetIndex + '.xml';
var arcName = self.prefix + '/' + fileName;
// Copy sheet file
self.archive.file(arcName, etree.tostring(sheet.root));
self.archive.files[arcName].options.binary = binary;
// copy sheet name in workbook
var newSheet = etree.SubElement(self.workbook.find('sheets'), 'sheet');
newSheet.attrib.name = copyName || 'Sheet' + newSheetIndex;
newSheet.attrib.sheetId = newSheetIndex;
newSheet.attrib['r:id'] = 'rId' + newSheetIndex;
// Copy definedName if any
self.workbook.findall('definedNames/definedName').forEach(element => {
if (element.text && element.text.split("!").length && element.text.split("!")[0] == sheetName) {
var newDefinedName = etree.SubElement(self.workbook.find('definedNames'), 'definedName', element.attrib);
newDefinedName.text = `${copyName}!${element.text.split("!")[1]}`;
newDefinedName.attrib.localSheetId = newSheetIndex - 1;
}
});
var newRel = etree.SubElement(self.workbookRels, 'Relationship');
newRel.attrib.Type = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet';
newRel.attrib.Target = fileName;
//Copy rels sheet - TODO : Maybe we can copy also the 'Target' files in rels, but Excel make this automaticly
var relFileName = 'worksheets' + '/_rels/' + 'sheet' + newSheetIndex + '.xml.rels';
var relArcName = self.prefix + '/' + relFileName;
self.archive.file(relArcName, etree.tostring(self.loadSheetRels(sheet.filename).root));
self.archive.files[relArcName].options.binary = true;
self._rebuild();
return self;
}
/**
* Partially rebuild after copy/delete sheets
*/
_rebuild() {
//each <sheet> 'r:id' attribute in '\xl\workbook.xml'
//must point to correct <Relationship> 'Id' in xl\_rels\workbook.xml.rels
var self = this;
var order = ['worksheet', 'theme', 'styles', 'sharedStrings'];
self.workbookRels.findall("*")
.sort(function (rel1, rel2) {
var index1 = order.indexOf(path.basename(rel1.attrib.Type));
var index2 = order.indexOf(path.basename(rel2.attrib.Type));
// If the attrib.Type is not in the order list, go to the end of sort
// Maybe we can do it more gracefully with the boolean operator
if (index1 < 0 && index2 >= 0)
return 1; // rel1 go after rel2
if (index1 >= 0 && index2 < 0)
return -1; // rel1 go before rel2
if (index1 < 0 && index2 < 0)
return 0; // change nothing
if ((index1 + index2) == 0) {
if (rel1.attrib.Id && rel2.attrib.Id)
return rel1.attrib.Id.substring(3) - rel2.attrib.Id.substring(3);
return rel1._id - rel2._id;
}
return index1 - index2;
})
.forEach(function (item, index) {
item.attrib.Id = 'rId' + (index + 1);
});
self.workbook.findall("sheets/sheet").forEach(function (item, index) {
item.attrib['r:id'] = 'rId' + (index + 1);
item.attrib.sheetId = (index + 1).toString();
});
self.archive.file(self.prefix + '/' + '_rels' + '/' + path.basename(self.workbookPath) + '.rels', etree.tostring(self.workbookRels));
self.archive.file(self.workbookPath, etree.tostring(self.workbook));
self.sheets = self.loadSheets(self.prefix, self.workbook, self.workbookRels);
}
/**
* Load a .xlsx file from a byte array.
*/
loadTemplate(data) {
var self = this;
if (Buffer.isBuffer(data)) {
data = data.toString('binary');
}
self.archive = new zip(data, { base64: false, checkCRC32: true });
// Load relationships
var rels = etree.parse(self.archive.file("_rels/.rels").asText()).getroot(), workbookPath = rels.find("Relationship[@Type='" + DOCUMENT_RELATIONSHIP + "']").attrib.Target;
self.workbookPath = workbookPath;
self.prefix = path.dirname(workbookPath);
self.workbook = etree.parse(self.archive.file(workbookPath).asText()).getroot();
self.workbookRels = etree.parse(self.archive.file(self.prefix + "/" + '_rels' + "/" + path.basename(workbookPath) + '.rels').asText()).getroot();
self.sheets = self.loadSheets(self.prefix, self.workbook, self.workbookRels);
self.calChainRel = self.workbookRels.find("Relationship[@Type='" + CALC_CHAIN_RELATIONSHIP + "']");
if (self.calChainRel) {
self.calcChainPath = self.prefix + "/" + self.calChainRel.attrib.Target;
}
self.sharedStringsPath = self.prefix + "/" + self.workbookRels.find("Relationship[@Type='" + SHARED_STRINGS_RELATIONSHIP + "']").attrib.Target;
self.sharedStrings = [];
etree.parse(self.archive.file(self.sharedStringsPath).asText()).getroot().findall('si').forEach(function (si) {
var t = { text: '' };
si.findall('t').forEach(function (tmp) {
t.text += tmp.text;
});
si.findall('r/t').forEach(function (tmp) {
t.text += tmp.text;
});
self.sharedStrings.push(t.text);
self.sharedStringsLookup[t.text] = self.sharedStrings.length - 1;
});
self.contentTypes = etree.parse(self.archive.file('[Content_Types].xml').asText()).getroot();
var jpgType = self.contentTypes.find('Default[@Extension="jpg"]');
if (jpgType === null) {
etree.SubElement(self.contentTypes, 'Default', { 'ContentType': 'image/png', 'Extension': 'jpg' });
}
}
/**
* Interpolate values for all the sheets using the given substitutions
* (an object).
*/
substituteAll(substitutions) {
var self = this;
var sheets = self.loadSheets(self.prefix, self.workbook, self.workbookRels);
sheets.forEach(function (sheet) {
self.substitute(sheet.id, substitutions);
});
}
/**
* Interpolate values for the sheet with the given number (1-based) or
* name (if a string) using the given substitutions (an object).
*/
substitute(sheetName, substitutions) {
var self = this;
var sheet = self.loadSheet(sheetName);
self.sheet = sheet;
var dimension = sheet.root.find("dimension"), sheetData = sheet.root.find("sheetData"), currentRow = null, totalRowsInserted = 0, totalColumnsInserted = 0, namedTables = self.loadTables(sheet.root, sheet.filename), rows = [], drawing = null;
var rels = self.loadSheetRels(sheet.filename);
sheetData.findall("row").forEach(function (row) {
row.attrib.r = currentRow = self.getCurrentRow(row, totalRowsInserted);
rows.push(row);
var cells = [], cellsInserted = 0, newTableRows = [], cellsForsubstituteTable = []; // Contains all the row cells when substitute tables
row.findall("c").forEach(function (cell) {
var appendCell = true;
cell.attrib.r = self.getCurrentCell(cell, currentRow, cellsInserted);
// If c[@t="s"] (string column), look up /c/v@text as integer in
// `this.sharedStrings`
if (cell.attrib.t === "s") {
// Look for a shared string that may contain placeholders
var cellValue = cell.find("v"), stringIndex = parseInt(cellValue.text, 10), string = self.sharedStrings[stringIndex];
if (string === undefined) {
return;
}
// Loop over placeholders
self.extractPlaceholders(string).forEach(function (placeholder) {
// Only substitute things for which we have a substitution
var substitution = _get(substitutions, placeholder.name, ''), newCellsInserted = 0;
if (placeholder.full && placeholder.type === "table" && substitution instanceof Array) {
if (placeholder.subType === 'image' && drawing == null) {
if (rels) {
drawing = self.loadDrawing(sheet.root, sheet.filename, rels.root);
} else {
console.log("Need to implement initRels. Or init this with Excel");
}
}
cellsForsubstituteTable.push(cell); // When substitute table, push (all) the cell
newCellsInserted = self.substituteTable(
row, newTableRows,
cells, cell,
namedTables, substitution, placeholder.key,
placeholder, drawing
);
// don't double-insert cells
// this applies to arrays only, incorrectly applies to object arrays when there a single row, thus not rendering single row
if (newCellsInserted !== 0 || substitution.length) {
if (substitution.length === 1) {
appendCell = true;
}
if (substitution[0][placeholder.key] instanceof Array) {
appendCell = false;
}
}
// Did we insert new columns (array values)?
if (newCellsInserted !== 0) {
cellsInserted += newCellsInserted;
self.pushRight(self.workbook, sheet.root, cell.attrib.r, newCellsInserted);
}
} else if (placeholder.full && placeholder.type === "normal" && substitution instanceof Array) {
appendCell = false; // don't double-insert cells
newCellsInserted = self.substituteArray(
cells, cell, substitution
);
if (newCellsInserted !== 0) {
cellsInserted += newCellsInserted;
self.pushRight(self.workbook, sheet.root, cell.attrib.r, newCellsInserted);
}
} else if (placeholder.type === "image" && placeholder.full) {
if (rels != null) {
if (drawing == null) {
drawing = self.loadDrawing(sheet.root, sheet.filename, rels.root);
}
string = self.substituteImage(cell, string, placeholder, substitution, drawing);
} else {
console.log("Need to implement initRels. Or init this with Excel");
}
} else if (placeholder.type === "imageincell" && placeholder.full) {
string = self.substituteImageInCell(cell, substitution);
} else {
if (placeholder.key) {
substitution = _get(substitutions, placeholder.name + '.' + placeholder.key);
}
string = self.substituteScalar(cell, string, placeholder, substitution);
}
});
}
// if we are inserting columns, we may not want to keep the original cell anymore
if (appendCell) {
cells.push(cell);
}
}); // cells loop
// We may have inserted columns, so re-build the children of the row
self.replaceChildren(row, cells);
// Update row spans attribute
if (cellsInserted !== 0) {
self.updateRowSpan(row, cellsInserted);
if (cellsInserted > totalColumnsInserted) {
totalColumnsInserted = cellsInserted;
}
}
// Add newly inserted rows
if (newTableRows.length > 0) {
// Move images for each subsitute array if option is active
if (self.option["moveImages"] && rels) {
if (drawing == null) {
// Maybe we can load drawing at the begining of function and remove all the self.loadDrawing() along the function ?
// If we make this, we create all the time the drawing file (like rels file at this moment)
drawing = self.loadDrawing(sheet.root, sheet.filename, rels.root);
}
if (drawing != null) {
self.moveAllImages(drawing, row.attrib.r, newTableRows.length);
}
}
// Filter all the cellsForsubstituteTable cell with the 'row' cell
var cellsOverTable = row.findall("c").filter(cell => !cellsForsubstituteTable.includes(cell));
newTableRows.forEach(function (row) {
if (self.option && self.option.subsituteAllTableRow) {
// I happend the other cell in substitute new table rows
cellsOverTable.forEach(function (cellOverTable) {
var newCell = self.cloneElement(cellOverTable);
newCell.attrib.r = self.joinRef({
row: row.attrib.r,
col: self.splitRef(newCell.attrib.r).col
});
row.append(newCell);
});
// I sort the cell in the new row
var newSortRow = row.findall("c").sort(function (a, b) {
var colA = self.splitRef(a.attrib.r).col;
var colB = self.splitRef(b.attrib.r).col;
return self.charToNum(colA) - self.charToNum(colB);
});
// And I replace the cell
self.replaceChildren(row, newSortRow);
}
rows.push(row);
++totalRowsInserted;
});
self.pushDown(self.workbook, sheet.root, namedTables, currentRow, newTableRows.length);
}
}); // rows loop
// We may have inserted rows, so re-build the children of the sheetData
self.replaceChildren(sheetData, rows);
// Update placeholders in table column headers
self.substituteTableColumnHeaders(namedTables, substitutions);
// Update placeholders in hyperlinks
self.substituteHyperlinks(rels, substitutions);
// Update <dimension /> if we added rows or columns
if (dimension) {
if (totalRowsInserted > 0 || totalColumnsInserted > 0) {
var dimensionRange = self.splitRange(dimension.attrib.ref), dimensionEndRef = self.splitRef(dimensionRange.end);
dimensionEndRef.row += totalRowsInserted;
dimensionEndRef.col = self.numToChar(self.charToNum(dimensionEndRef.col) + totalColumnsInserted);
dimensionRange.end = self.joinRef(dimensionEndRef);
dimension.attrib.ref = self.joinRange(dimensionRange);
}
}
//Here we are forcing the values in formulas to be recalculated
// existing as well as just substituted
sheetData.findall("row").forEach(function (row) {
row.findall("c").forEach(function (cell) {
var formulas = cell.findall('f');
if (formulas && formulas.length > 0) {
cell.findall('v').forEach(function (v) {
cell.remove(v);
});
}
});
});
// Write back the modified XML trees
self.archive.file(sheet.filename, etree.tostring(sheet.root));
self.archive.file(self.workbookPath, etree.tostring(self.workbook));
if (rels) {
self.archive.file(rels.filename, etree.tostring(rels.root));
}
self.writeRichData();
self.archive.file('[Content_Types].xml', etree.tostring(self.contentTypes));
// Remove calc chain - Excel will re-build, and we may have moved some formulae
if (self.calcChainPath && self.archive.file(self.calcChainPath)) {
self.archive.remove(self.calcChainPath);
}
self.writeSharedStrings();
self.writeTables(namedTables);
self.writeDrawing(drawing);
}
/**
* Generate a new binary .xlsx file
*/
generate(options) {
var self = this;
if (!options) {
options = {
base64: false
};
}
return self.archive.generate(options);
}
// Helpers
// Write back the new shared strings list
writeSharedStrings() {
var self = this;
var root = etree.parse(self.archive.file(self.sharedStringsPath).asText()).getroot(), children = root.getchildren();
root.delSlice(0, children.length);
self.sharedStrings.forEach(function (string) {
var si = new etree.Element("si"), t = new etree.Element("t");
t.text = string;
si.append(t);
root.append(si);
});
root.attrib.count = self.sharedStrings.length;
root.attrib.uniqueCount = self.sharedStrings.length;
self.archive.file(self.sharedStringsPath, etree.tostring(root));
}
// Add a new shared string
addSharedString(s) {
var self = this;
var idx = self.sharedStrings.length;
self.sharedStrings.push(s);
self.sharedStringsLookup[s] = idx;
return idx;
}
// Get the number of a shared string, adding a new one if necessary.
stringIndex(s) {
var self = this;
var idx = self.sharedStringsLookup[s];
if (idx === undefined) {
idx = self.addSharedString(s);
}
return idx;
}
// Replace a shared string with a new one at the same index. Return the
// index.
replaceString(oldString, newString) {
var self = this;
var idx = self.sharedStringsLookup[oldString];
if (idx === undefined) {
idx = self.addSharedString(newString);
} else {
self.sharedStrings[idx] = newString;
delete self.sharedStringsLookup[oldString];
self.sharedStringsLookup[newString] = idx;
}
return idx;
}
// Get a list of sheet ids, names and filenames
loadSheets(prefix, workbook, workbookRels) {
var sheets = [];
workbook.findall("sheets/sheet").forEach(function (sheet) {
var sheetId = sheet.attrib.sheetId, relId = sheet.attrib['r:id'], relationship = workbookRels.find("Relationship[@Id='" + relId + "']"), filename = prefix + "/" + relationship.attrib.Target;
sheets.push({
id: parseInt(sheetId, 10),
name: sheet.attrib.name,
filename: filename
});
});
return sheets;
}
// Get sheet a sheet, including filename and name
loadSheet(sheet) {
var self = this;
var info = null;
for (var i = 0; i < self.sheets.length; ++i) {
if ((typeof (sheet) === "number" && self.sheets[i].id === sheet) || (self.sheets[i].name === sheet)) {
info = self.sheets[i];
break;
}
}
if (info === null && (typeof (sheet) === "number")) {
//Get the sheet that corresponds to the 0 based index if the id does not work
info = self.sheets[sheet - 1];
}
if (info === null) {
throw new Error("Sheet " + sheet + " not found");
}
return {
filename: info.filename,
name: info.name,
id: info.id,
root: etree.parse(self.archive.file(info.filename).asText()).getroot()
};
}
//Load rels for a sheetName
loadSheetRels(sheetFilename) {
var self = this;
var sheetDirectory = path.dirname(sheetFilename), sheetName = path.basename(sheetFilename), relsFilename = path.join(sheetDirectory, '_rels', sheetName + '.rels').replace(/\\/g, '/'), relsFile = self.archive.file(relsFilename);
if (relsFile === null) {
return self.initSheetRels(sheetFilename);
}
var rels = { filename: relsFilename, root: etree.parse(relsFile.asText()).getroot() };
return rels;
}
initSheetRels(sheetFilename) {
var sheetDirectory = path.dirname(sheetFilename), sheetName = path.basename(sheetFilename), relsFilename = path.join(sheetDirectory, '_rels', sheetName + '.rels').replace(/\\/g, '/');
var element = etree.Element;
var ElementTree = etree.ElementTree;
var root = element('Relationships');
root.set('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
var relsEtree = new ElementTree(root);
var rels = { filename: relsFilename, root: relsEtree.getroot() };
return rels;
}
// Load Drawing file
loadDrawing(sheet, sheetFilename, rels) {
var self = this;
var sheetDirectory = path.dirname(sheetFilename), sheetName = path.basename(sheetFilename), drawing = { filename: '', root: null };
var drawingPart = sheet.find("drawing");
if (drawingPart === null) {
drawing = self.initDrawing(sheet, rels);
return drawing;
}
var relationshipId = drawingPart.attrib['r:id'], target = rels.find("Relationship[@Id='" + relationshipId + "']").attrib.Target, drawingFilename = path.join(sheetDirectory, target).replace(/\\/g, '/'), drawingTree = etree.parse(self.archive.file(drawingFilename).asText());
drawing.filename = drawingFilename;
drawing.root = drawingTree.getroot();
drawing.relFilename = path.dirname(drawingFilename) + '/_rels/' + path.basename(drawingFilename) + '.rels';
drawing.relRoot = etree.parse(self.archive.file(drawing.relFilename).asText()).getroot();
return drawing;
}
addContentType(partName, contentType) {
var self = this;
etree.SubElement(self.contentTypes, 'Override', { 'ContentType': contentType, 'PartName': partName });
}
initDrawing(sheet, rels) {
var self = this;
var maxId = self.findMaxId(rels, 'Relationship', 'Id', /rId(\d*)/);
var rel = etree.SubElement(rels, 'Relationship');
sheet.insert(sheet._children.length, etree.Element('drawing', { 'r:id': 'rId' + maxId }));
rel.set('Id', 'rId' + maxId);
rel.set('Type', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing');
var drawing = {};
var drawingFilename = 'drawing' + self.findMaxFileId(/xl\/drawings\/drawing\d*\.xml/, /drawing(\d*)\.xml/) + '.xml';
rel.set('Target', '../drawings/' + drawingFilename);
drawing.root = etree.Element('xdr:wsDr');
drawing.root.set('xmlns:xdr', "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing");
drawing.root.set('xmlns:a', "http://schemas.openxmlformats.org/drawingml/2006/main");
drawing.filename = 'xl/drawings/' + drawingFilename;
drawing.relFilename = 'xl/drawings/_rels/' + drawingFilename + '.rels';
drawing.relRoot = etree.Element('Relationships');
drawing.relRoot.set('xmlns', "http://schemas.openxmlformats.org/package/2006/relationships");
self.addContentType('/' + drawing.filename, 'application/vnd.openxmlformats-officedocument.drawing+xml');
return drawing;
}
// Write Drawing file
writeDrawing(drawing) {
var self = this;
if (drawing !== null) {
self.archive.file(drawing.filename, etree.tostring(drawing.root));
self.archive.file(drawing.relFilename, etree.tostring(drawing.relRoot));
}
}
// Move all images after fromRow of nbRow row
moveAllImages(drawing, fromRow, nbRow) {
var self = this;
drawing.root.getchildren().forEach(function (drawElement) {
if (drawElement.tag == "xdr:twoCellAnchor") {
self._moveTwoCellAnchor(drawElement, fromRow, nbRow);
}
// TODO : make the other tags image
});
}
// Move TwoCellAnchor tag images after fromRow of nbRow row
_moveTwoCellAnchor(drawingElement, fromRow, nbRow) {
var self = this;
var _moveImage = function (drawingElement, fromRow, nbRow) {
var from = Number.parseInt(drawingElement.find('xdr:from').find('xdr:row').text, 10) + Number.parseInt(nbRow, 10);
drawingElement.find('xdr:from').find('xdr:row').text = from;
var to = Number.parseInt(drawingElement.find('xdr:to').find('xdr:row').text, 10) + Number.parseInt(nbRow, 10);
drawingElement.find('xdr:to').find('xdr:row').text = to;
};
if (self.option["moveSameLineImages"]) {
if (parseInt(drawingElement.find('xdr:from').find('xdr:row').text) + 1 >= fromRow) {
_moveImage(drawingElement, fromRow, nbRow);
}
} else {
if (parseInt(drawingElement.find('xdr:from').find('xdr:row').text) + 1 > fromRow) {
_moveImage(drawingElement, fromRow, nbRow);
}
}
}
// Load tables for a given sheet
loadTables(sheet, sheetFilename) {
var self = this;
var sheetDirectory = path.dirname(sheetFilename), sheetName = path.basename(sheetFilename), relsFilename = sheetDirectory + "/" + '_rels' + "/" + sheetName + '.rels', relsFile = self.archive.file(relsFilename), tables = []; // [{filename: ..., root: ....}]
if (relsFile === null) {
return tables;
}
var rels = etree.parse(relsFile.asText()).getroot();
sheet.findall("tableParts/tablePart").forEach(function (tablePart) {
var relationshipId = tablePart.attrib['r:id'], target = rels.find("Relationship[@Id='" + relationshipId + "']").attrib.Target, tableFilename = target.replace('..', self.prefix), tableTree = etree.parse(self.archive.file(tableFilename).asText());
tables.push({
filename: tableFilename,
root: tableTree.getroot()
});
});
return tables;
}
// Write back possibly-modified tables
writeTables(tables) {
var self = this;
tables.forEach(function (namedTable) {
self.archive.file(namedTable.filename, etree.tostring(namedTable.root));
});
}
//Perform substitution in hyperlinks
substituteHyperlinks(rels, substitutions) {
let self = this;
etree.parse(self.archive.file(self.sharedStringsPath).asText()).getroot();
if (rels === null) {
return;
}
const relationships = rels.root._children;
relationships.forEach(function (relationship) {
if (relationship.attrib.Type === HYPERLINK_RELATIONSHIP) {
let target = relationship.attrib.Target;
//Double-decode due to excel double encoding url placeholders
target = decodeURI(decodeURI(target));
self.extractPlaceholders(target).forEach(function (placeholder) {
const substitution = substitutions[placeholder.name];
if (substitution === undefined) {
return;
}
target = target.replace(placeholder.placeholder, self.stringify(substitution));
relationship.attrib.Target = encodeURI(target);
}
);
}
});
}
// Perform substitution in table headers
substituteTableColumnHeaders(tables, substitutions) {
var self = this;
tables.forEach(function (table) {
var root = table.root, columns = root.find("tableColumns"), autoFilter = root.find("autoFilter"), tableRange = self.splitRange(root.attrib.ref), idx = 0, inserted = 0, newColumns = [];
columns.findall("tableColumn").forEach(function (col) {
++idx;
col.attrib.id = Number(idx).toString();
newColumns.push(col);
var name = col.attrib.name;
self.extractPlaceholders(name).forEach(function (placeholder) {
var substitution = substitutions[placeholder.name];
if (substitution === undefined) {
return;
}
// Array -> new columns
if (placeholder.full && placeholder.type === "normal" && substitution instanceof Array) {
substitution.forEach(function (element, i) {
var newCol = col;
if (i > 0) {
newCol = self.cloneElement(newCol);
newCol.attrib.id = Number(++idx).toString();
newColumns.push(newCol);
++inserted;
tableRange.end = self.nextCol(tableRange.end);
}
newCol.attrib.name = self.stringify(element);
});
// Normal placeholder
} else {
name = name.replace(placeholder.placeholder, self.stringify(substitution));
col.attrib.name = name;
}
});
});
self.replaceChildren(columns, newColumns);
// Update range if we inserted columns
if (inserted > 0) {
columns.attrib.count = Number(idx).toString();
root.attrib.ref = self.joinRange(tableRange);
if (autoFilter !== null) {
// XXX: This is a simplification that may stomp on some configurations
autoFilter.attrib.ref = self.joinRange(tableRange);
}
}
//update ranges for totalsRowCount
var tableRoot = table.root, tableRange = self.splitRange(tableRoot.attrib.ref), tableStart = self.splitRef(tableRange.start), tableEnd = self.splitRef(tableRange.end);
if (tableRoot.attrib.totalsRowCount) {
var autoFilter = tableRoot.find("autoFilter");
if (autoFilter !== null) {
autoFilter.attrib.ref = self.joinRange({
start: self.joinRef(tableStart),
end: self.joinRef(tableEnd),
});
}
++tableEnd.row;
tableRoot.attrib.ref = self.joinRange({
start: self.joinRef(tableStart),
end: self.joinRef(tableEnd),
});
}
});
}
// Return a list of tokens that may exist in the string.
// Keys are: `placeholder` (the full placeholder, including the `${}`
// delineators), `name` (the name part of the token), `key` (the object key
// for `table` tokens), `full` (boolean indicating whether this placeholder
// is the entirety of the string) and `type` (one of `table` or `cell`)
extractPlaceholders(string) {
// Yes, that's right. It's a bunch of brackets and question marks and stuff.
var re = /\${(?:(.+?):)?(.+?)(?:\.(.+?))?(?::(.+?))??}/g;
var match = null, matches = [];
while ((match = re.exec(string)) !== null) {
matches.push({
placeholder: match[0],
type: match[1] || 'normal',
name: match[2],
key: match[3],
subType: match[4],
full: match[0].length === string.length
});
}
return matches;
}
// Split a reference into an object with keys `row` and `col` and,
// optionally, `table`, `rowAbsolute` and `colAbsolute`.
splitRef(ref) {
var match = ref.match(/(?:(.+)!)?(\$)?([A-Z]+)?(\$)?([0-9]+)/);
return {
table: match && match[1] || null,
colAbsolute: Boolean(match && match[2]),
col: match && match[3] || "",
rowAbsolute: Boolean(match && match[4]),
row: parseInt(match && match[5], 10)
};
}
// Join an object with keys `row` and `col` into a single reference string
joinRef(ref) {
return (ref.table ? ref.table + "!" : "") +
(ref.colAbsolute ? "$" : "") +
ref.col.toUpperCase() +
(ref.rowAbsolute ? "$" : "") +
Number(ref.row).toString();
}
// Get the next column's cell reference given a reference like "B2".
nextCol(ref) {
var self = this;
ref = ref.toUpperCase();
return ref.replace(/[A-Z]+/, function (match) {
return self.numToChar(self.charToNum(match) + 1);
});
}
// Get the next row's cell reference given a reference like "B2".
nextRow(ref) {
ref = ref.toUpperCase();
return ref.replace(/[0-9]+/, function (match) {
return (parseInt(match, 10) + 1).toString();
});
}
// Turn a reference like "AA" into a number like 27
charToNum(str) {
var num = 0;
for (var idx = str.length - 1, iteration = 0; idx >= 0; --idx, ++iteration) {
var thisChar = str.charCodeAt(idx) - 64, // A -> 1; B -> 2; ... Z->26
multiplier = Math.pow(26, iteration);
num += multiplier * thisChar;
}
return num;
}
// Turn a number like 27 into a reference like "AA"
numToChar(num) {
var str = "";
for (var i = 0; num > 0; ++i) {
var remainder = num % 26, charCode = remainder + 64;
num = (num - remainder) / 26;
// Compensate for the fact that we don't represent zero, e.g. A = 1, Z = 26, but AA = 27
if (remainder === 0) { // 26 -> Z
charCode = 90;
--num;
}
str = String.fromCharCode(charCode) + str;
}
return str;
}
// Is ref a range?
isRange(ref) {
return ref.indexOf(':') !== -1;
}
// Is ref inside the table defined by startRef and endRef?
isWithin(ref, startRef, endRef) {
var self = this;
var start = self.splitRef(startRef), end = self.splitRef(endRef), target = self.splitRef(ref);
start.col = self.charToNum(start.col);
end.col = self.charToNum(end.col);
target.col = self.charToNum(target.col);
return (
start.row <= target.row && target.row <= end.row &&
start.col <= target.col && target.col <= end.col
);
}
// Turn a value of any type into a string
stringify(value) {
if (value instanceof Date) {
//In Excel date is a number of days since 01/01/1900
// timestamp in ms to days + number of days from 1900 to 1970
return Number((value.getTime() / (1000 * 60 * 60 * 24)) + 25569);
} else if (typeof (value) === "number" || typeof (value) === "boolean") {
return Number(value).toString();
} else if (typeof (value) === "string") {
return String(value).toString();
}
return "";
}
// Insert a substitution value into a cell (c tag)
insertCellValue(cell, substitution) {
var self = this;
var cellValue = cell.find("v"), stringified = self.stringify(substitution);
if (typeof substitution === 'string' && substitution[0] === '=') {
//substitution, started with '=' is a formula substitution
var formula = new etree.Element("f");
formula.text = substitution.substr(1);
cell.insert(1, formula);
delete cell.attrib.t; //cellValue will be deleted later
return formula.text;
}
if (typeof (substitution) === "number" || substitution instanceof Date) {
delete cell.attrib.t;
cellValue.text = stringified;
} else if (typeof (substitution) === "boolean") {
cell.attrib.t = "b";
cellValue.text = stringified;
} else {
cell.attrib.t = "s";
cellValue.text = Number(self.stringIndex(stringified)).toString();
}
return stringified;
}
// Perform substitution of a single value
substituteScalar(cell, string, placeholder, substitution) {
var self = this;
if (placeholder.full) {
return self.insertCellValue(cell, substitution);
} else {
var newString = string.replace(placeholder.placeholder, self.stringify(substitution));
cell.attrib.t = "s";
return self.insertCellValue(cell, newString);
}
}
// Perform a columns substitution from an array
substituteArray(cells, cell, substitution) {
var self = this;
var newCellsInserted = -1, // we technically delete one before we start adding back
currentCell = cell.attrib.r;
// add a cell for each element in the list
substitution.forEach(function (element) {
++newCellsInserted;
if (newCellsInserted > 0) {
currentCell = self.nextCol(currentCell);
}
var newCell = self.cloneElement(cell);
self.insertCellValue(newCell, element);
newCell.attrib.r = currentCell;
cells.push(newCell);
});
return newCellsInserted;
}
// Perform a table substitution. May update `newTableRows` and `cells` and change `cell`.
// Returns total number of new cells inserted on the original row.
substituteTable(row, newTableRows, cells, cell, namedTables, substitution, key, placeholder, drawing) {
var self = this, newCellsInserted = 0; // on the original row
// if no elements, blank the cell, but don't delete it
if (substitution.length === 0) {
delete cell.attrib.t;
self.replaceChildren(cell, []);
} else {