/
ExportSheetData.gs
1878 lines (1564 loc) · 59.5 KB
/
ExportSheetData.gs
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
var esdVersion = 52;
//Popup message
var messageLineHeight = 10;
//Indenting
var indentValue = " ";
var indentAmount = 0;
//Subpath types
var jsonArraySubpath = "Array"; //JSON Array
var jsonObjectSubpath = "Object"; //JSON Object
var xmlArraySubpath = "Array"; //XML element with child elements
var xmlAttributeSubpath = "Attibute"; //XML element attribute
var keySubpath = "Key"; //JSON field or XML element key
//Search types
var searchTypeField = "Field"; //Search for a specific field value (#FIELD_ID)
var searchTypeRoot = "Root"; //Set the target element to the root JSON object (#ROOT)
var searchTypeSheet = "Sheet"; //Set the target element to the sheet's root. (#SHEET)
var searchTypeRow = "Row"; //Search for the index matching a row's index (#ROW)
var searchTypeIndex = "Index"; //Search for a specific index (#1)
var searchTypeNone = "None"; //Not a valid search type
//Special prefixes to allow XML nested elements
//var arrayPref = "ARRAY_";
//var attributePref = "ATTRIBUTE_";
//Gets the last settings for ESD in the open document.
function getProperties()
{
var properties = PropertiesService.getDocumentProperties();
return JSON.stringify(properties.getProperties());
}
//Saves the settings last used for ESD so the user doesn't need to reselect them next time ESD is opened.
function setProperties(newProperties)
{
var properties = PropertiesService.getDocumentProperties();
properties.setProperties(JSON.parse(newProperties));
}
//Gets the total export settings for ESD in the open document.
function getExportProperties()
{
var props = PropertiesService.getDocumentProperties();
var prop = props.getProperty("settings");
return prop;
}
//Saves the total export settings for ESD in the open document so the user doesn't need to reselect them next time ESD is opened.
function setExportProperties(newProperties)
{
var properties = PropertiesService.getDocumentProperties();
var prop = properties.getProperty("settings");
properties.setProperty("settings", newProperties);
}
//Gets the settings used in the last export.
function getPrevExportProperties()
{
var props = PropertiesService.getDocumentProperties();
var prop = props.getProperty("prev");
return prop;
}
//Saves the settings used in the last export.
function setPrevExportProperties(newProperties)
{
var properties = PropertiesService.getDocumentProperties();
properties.setProperty("prev", newProperties);
}
//Get the ESD properties for a specific user.
function getUserProperties()
{
var properties = PropertiesService.getUserProperties();
return JSON.stringify(properties.getProperties());
}
//Saves user settings for ESD.
function setUserProperties(newProperties)
{
var properties = PropertiesService.getUserProperties();
properties.setProperties(JSON.parse(newProperties));
}
//Get the current version of ESD.
function getVersion()
{
return esdVersion;
}
//Returns true if the passed value is an array.
function isArray(array)
{
return Array.isArray(array);
}
//Returns true if the pased value is an object and is not null.
function isObject(object)
{
return (typeof(object) === 'object' && object !== null);
}
//Returns true if the passed value is undefined.
function isUndefined(value)
{
return (typeof(value) === 'undefined');
}
//Returns the index of the given value in an array.
function getIndexOf(array, value)
{
if(!isArray(array)) return -1;
var index = -1;
for(var i=0; i < array.length; i++)
{
if(array[i] == value)
{
index = i;
break;
}
}
return index;
}
//Gets the number of indents to use when formatting
function getIndent()
{
var indent = "";
for(var i=0; i < indentAmount; i++)
{
indent += indentValue;
}
return indent;
}
//Gets all of the sheet names in the current spreadsheet
function getSheetNames()
{
var spreadsheet = SpreadsheetApp.getActive();
var sheets = spreadsheet.getSheets();
var sheetNames = new Array();
for(var i=0; i < sheets.length; i++)
{
sheetNames.push(sheets[i].getName());
}
return sheetNames;
}
//Gets the active sheet name in the current spreadsheet
function getActiveSheetName()
{
var spreadsheet = SpreadsheetApp.getActive();
return spreadsheet.getActiveSheet().getName();
}
//Gets a file's parent folder
function getFileParentFolder(file)
{
var folders = file.getParents();
var parentFolder;
while(folders.hasNext())
{
parentFolder = folders.next();
}
return parentFolder;
}
//Gets a file's parent folder's ID, or the root Drive folder ID if the parent folder is null
function getFileParentFolderId(file)
{
var folder = getFileParentFolder(file);
if(folder == null)
{
folder = DriveApp.getRootFolder();
}
return folder.getId();
}
function getCellContentArray(cell, separatorChar)
{
var content = cell;
var cellArray = new Array();
var commaIndicies = new Array();
var openQuoteIndicies = new Array();
var closeQuoteIndicies = new Array();
//Set the indicies for quotes and commas
for(var i=0; i < content.length; i++)
{
if(content.charAt(i) == '"')
{
if(openQuoteIndicies.length == closeQuoteIndicies.length)
{
openQuoteIndicies.push(i);
}
else
{
closeQuoteIndicies.push(i);
}
}
else if(content.charAt(i) == separatorChar)
{
commaIndicies.push(i);
}
}
//Remove a comma if it is wrapped in quotes
//Use the close quote indicies in the case of an open ended quote at the end of content
for(var i=0; i < closeQuoteIndicies.length; i++)
{
for(var j=commaIndicies.length-1; j >= 0; j--)
{
if(commaIndicies[j] > openQuoteIndicies[i] && commaIndicies[j] < closeQuoteIndicies[i])
{
commaIndicies.splice(j, 1);
}
}
}
//populate the array
var startIndex = 0;
for(var i=0; i < commaIndicies.length; i++)
{
var arrayString = content.slice(startIndex, commaIndicies[i]);
if(arrayString != "") cellArray.push(arrayString.replace('"', ' ').replace('"', ' ').trim()); //Get rid of the wrapping quotes
startIndex = commaIndicies[i] + 1; // +1 so the next string doesn't start with a comma
}
if(commaIndicies.length > 0)
{
var endIndex;
if(content[content.length - 1] == separatorChar) endIndex = content.length - 1;
else endIndex = content.length;
var lastString = content.slice(startIndex, endIndex); //Push the string from the last comma to the end of the content string
cellArray.push(lastString.replace('"', ' ').replace('"', ' ').trim()); //Get rid of wrapping quotes
}
if(commaIndicies.length == 0) // If there are no commas to make the array, return the whole content
{
cellArray.push(content);
}
//Convert values to their correct type (float, bool, etc)
for(var i=0; i < cellArray.length; i++)
{
if(!isNaN(parseFloat(cellArray[i])))
{
var isNumber = true;
var minusCount = 0;
var decimalCount = 0;
//Parse float is unreliable, so loop through to make sure the string is actually a float
for(var j=0; j < cellArray[i].length; j++)
{
if(isNaN(cellArray[i][j]))
{
if(cellArray[i][j] === '.')
{
if(decimalCount > 0)
{
isNumber = false;
break;
}
else
{
decimalCount++;
}
}
else if(cellArray[i][j] === '-')
{
if(minusCount > 0)
{
isNumber = false;
break;
}
else
{
minusCount++;
}
}
else
{
isNumber = false;
break;
}
}
}
if(isNumber) cellArray[i] = parseFloat(cellArray[i]);
}
else if(cellArray[i] === 'true') cellArray[i] = true;
else if(cellArray[i] === 'false') cellArray[i] = false;
}
return cellArray;
}
//Formats a string to adhere to XML element naming conventions
//See: https://www.w3schools.com/xml/xml_elements.asp
function formatXmlName(value, replacement)
{
var xmlName = value;
if(!isNaN(value)) xmlName = "_" + value.toString();
else if(!isNaN(value[0])) xmlName = "_" + value; //XML element names cannot start with a number, so add a "_" to the start of the name
if(xmlName.length >= 3)
{
if(xmlName.toLowerCase().indexOf("xml") === 0)
{
xmlName = "_" + xmlName; //XML element names cannot start with "XML" so add an underscore to the front
}
}
xmlName = xmlName.replace(/[^a-zA-Z0-9\-\_]/gm, replacement); //Replace non-alphanumeric, dash, underscore, or period chars with an underscore
if(xmlName.search(/[a-zA-Z\_]/g) > 0)
{
xmlName = "_" + xmlName; //XML element names must start with a letter or underscore, so add an underscore to the front
}
return xmlName;
}
function formatJsonString(value, asObject)
{
if(value.length > 1)
{
//Get rid of wrapping quotes (")
if(value[0] == '"' && value[value.length-1] == '"')
{
var endValue = value.length - 1;
if(endValue < 1) endValue = 1;
value = value.substring(1, endValue);
}
//Don't format object values (wrapped with {})
if(asObject && value[0] == '{' && value[value.length-1] == '}')
{
//Need to format to match the rest of the file
return value;
}
}
return JSON.stringify(value);
}
//Returns true if a key starts with the specified prefix.
function keyHasPrefix(key, prefix)
{
if(prefix.length > key.length || prefix.length === 0) return false;
var newKey = "";
for(var i=0; i < prefix.length; i++)
{
newKey += key[i];
}
return newKey === prefix;
}
//Returns true if a key starts with any of the specified prefixes.
function keyHasPrefixes(key, prefixes)
{
for(var i=0; i < prefixes.length; i++)
{
if(keyHasPrefix(key, prefixes[i]))
{
return true;
}
}
return false;
}
//Returns an array indicating if specific prefixes are used in a given key.
//Multiple string values can be passed in for the prefixes argument.
function getPrefixes(key, prefixes)
{
var values = new Array();
var prefixArgs = new Array();
//Set initial values
for(var i=1; i < arguments.length; i++)
{
values.push(false);
prefixArgs.push(arguments[i]);
}
//Loop through and set if each prefix is used.
while(keyHasPrefixes(key, prefixArgs))
{
for(var i=1; i < arguments.length; i++)
{
if(keyHasPrefix(key, arguments[i]))
{
values[i-1] = true;
key = stripPrefix(key, arguments[i]); //Strip the prefix from the key and start the loop again.
}
}
}
return values;
}
//Strips a given prefix from the passed key (so prefixes like forced JSON arrays' JA_ are not included in the actual exported key value)
function stripPrefix(key, prefix)
{
if(keyHasPrefix(key, prefix) === true)
{
var newKey = "";
for(var i=prefix.length; i < key.length; i++)
{
newKey += key[i];
}
return newKey;
}
return key;
}
//Strips the specified prefixes from the passed key.
function stripPrefixes(key, prefixes)
{
var prefixArgs = new Array();
//Set initial values
for(var i=1; i < arguments.length; i++)
{
prefixArgs.push(arguments[i]);
}
//Loop through and set if each prefix is used.
while(keyHasPrefixes(key, prefixArgs))
{
for(var i=1; i < arguments.length; i++)
{
if(keyHasPrefix(key, arguments[i]))
{
key = stripPrefix(key, arguments[i]); //Strip the prefix from the key and start the loop again.
}
}
}
return key;
}
//Is the subpath a search pattern (prefixed with #), or is it a hardset path
function isSearchSubpath(subpath)
{
return subpath.length > 0 ? subpath[0] === '#' : false;
}
//TODO: Remove index paths? ({#1}, {#ID}, etc)
//That will only cover paths that end in an index, not paths with multiple indexes in their center... Should add implicit values to path string instead?
//Actually, should function since implied indexes are set as a path iterates
function getKeyPathString(path, index)
{
var pathstring = "";
for(var i=0; i < path.length; i++)
{
if(index <= i) break;
if(path[i].length <= 2 || path[i][1] !== '#') pathstring += path[i]; //Only add the suppath if it is not a search path
}
return pathstring;
}
//Returns an array representing a key separated into subpaths. Used for nested objects
function getKeyPath(key, implicitNames, implicitValues, nestedElements)
{
var path = [];
if(!keyHasPrefix(key, '[') && !keyHasPrefix(key, '{') || !nestedElements) //TODO: Need to strip out special prefixes like NOEX_
{
path.push(key);
}
else
{
var subPath = "";
var pathType = "";
for(var i=0; i < key.length; i++)
{
if(pathType === "") pathType = key[i];
subPath += key[i];
if((pathType === '[' && key[i] === ']') || (pathType === '{' && key[i] === '}'))
{
path.push(subPath);
//Inject implied values when needed and able
if(pathType === '[' && i < key.length-1 && key[i+1] !== '{')
{
var pathInjectString = getKeyPathString(path, path.length);
if(getIndexOf(implicitNames, pathInjectString) >= 0)
{
path.push("{#" + (implicitValues[getIndexOf(implicitNames, pathInjectString)] + 1) + "}");
}
}
subPath = "";
pathType = "";
}
}
if(subPath.length > 0) path.push(subPath);
//Check that the last element in the path is a key path type. If not, make one from the last existing element.
if(getSubpathTypeJson(path[path.length-1]) !== keySubpath)
{
var keyPath = trimKeySubpath(path[path.length-1]);
if(isSearchSubpath(keyPath)) keyPath = keyPath.substring(1);
//If the last part of the key path is a number, make the last key path an actual Number
//if(!isNaN(keyPath)) keyPath = Number(keyPath);
path.push(keyPath);
}
}
return path;
}
function trimKeySubpath(key)
{
return key.substring(1, key.length-1);
}
function getSubpathTypeXml(subpath)
{
var type = keySubpath;
if(subpath.length > 0)
{
switch(subpath[0])
{
case '[':
type = xmlArraySubpath;
break;
case '{':
type = xmlAttributeSubpath;
break;
}
}
return type;
}
//gets the type of a subpath in a JSON export nested element key.
function getSubpathTypeJson(subpath)
{
var type = keySubpath;
if(subpath.length > 0)
{
switch(subpath[0])
{
case '[':
type = jsonArraySubpath;
break;
case '{':
type = jsonObjectSubpath;
break;
}
}
return type;
}
//What type of search does the subpath indicate?
function getSubpathSearchType(subpath)
{
var type = searchTypeNone;
if(subpath.length > 0)
{
//subpath = subpath.substring(1);
if(!isNaN(Number(subpath))) //Index
{
type = searchTypeIndex;
}
//TODO: This can only work if sheetJsonArray/Object are added to the root object first...
/*else if(subpath == "ROOT")
{
type = searchTypeRoot;
}*/
else if(subpath == "SHEET")
{
type = searchTypeSheet;
}
else if(subpath == "ROW") //Row based index
{
type = searchTypeRow;
}
else //Field
{
type = searchTypeField;
}
}
return type;
}
function exportXml(formatSettings)
{
showCompilingMessage('Compiling XML...');
exportSpreadsheetXml(formatSettings);
var tempSettings = JSON.parse(formatSettings);
tempSettings["visualize"] = false;
formatSettings = JSON.stringify(tempSettings);
setPrevExportProperties(formatSettings);
}
function exportJson(formatSettings)
{
showCompilingMessage('Compiling JSON...');
exportSpreadsheetJson(formatSettings);
var tempSettings = JSON.parse(formatSettings);
tempSettings["visualize"] = false;
formatSettings = JSON.stringify(tempSettings);
setPrevExportProperties(formatSettings);
}
function exportSpreadsheetXml(formatSettings)
{
//Settings
var settings = JSON.parse(formatSettings);
//File settings
var visualize = settings["visualize"];
var singleSheet = settings["singleSheet"];
var replaceFile = settings["replaceExistingFiles"];
var unwrap = settings["unwrapSingleRows"];
var collapse = settings["collapseSingleRows"];
var ignoreEmpty = settings["ignoreEmptyCells"];
var nestedElements = settings["nestedElements"];
var minifyData = settings["minifyData"];
var ignorePrefix = settings["ignorePrefix"];
var unwrapPrefix = settings["unwrapPrefix"];
var collapsePrefix = settings["collapsePrefix"];
var customSheets = settings["targetSheets"];
//XML settings
var useChildElements = settings["exportChildElements"];
var includeFirstColumnXml = settings["includeFirstColumn"];
var rootElement = settings["rootElement"];
var nameReplacementChar = settings["nameReplacementChar"];
var declarationVersion = settings["declarationVersion"];
var declarationEncoding = settings["declarationEncoding"];
var declarationStandalone = settings["declarationStandalone"];
var attributePrefix = settings["attributePrefix"];
var childElementPrefix = settings["childElementPrefix"];
var innerTextPrefix = settings["innerTextPrefix"];
//Sheets info
var spreadsheet = SpreadsheetApp.getActive();
var sheets = spreadsheet.getSheets();
var exportMessage = "";
var exportMessageHeight = 0;
if(customSheets != null)
{
var exportSheets = sheets;
sheets = new Array();
for(var i=0; i < exportSheets.length; i++)
{
if(customSheets[exportSheets[i].getName()] === 'true')
{
if(spreadsheet.getSheetByName(exportSheets[i].getName()) != null)
{
sheets.push(spreadsheet.getSheetByName(exportSheets[i].getName()));
}
}
}
}
var fileName = spreadsheet.getName() + (singleSheet ? (" - " + sheets[0].getName()) : "") + ".xml";
var sheetValues = [[]];
var xmlRoot = XmlService.createElement(formatXmlName(rootElement, nameReplacementChar)); //Create the root XML element. https://developers.google.com/apps-script/reference/xml-service/
for(var i=0; i < sheets.length; i++)
{
var sheetName = sheets[i].getName();
var range = sheets[i].getDataRange();
var values = range.getValues();
var rows = range.getNumRows();
var columns = range.getNumColumns();
var unwrapSheet = unwrap && rows <= 2;
var collapseSheet = collapse && rows <= 2;
var forceUnwrap = false;
var forceCollapse = false;
//Get the prefixes used by this sheet
var activePrefixes = getPrefixes(sheetName, unwrapPrefix, collapsePrefix);
sheetName = stripPrefixes(sheetName, unwrapPrefix, collapsePrefix);
var sheetXml = XmlService.createElement(formatXmlName(sheetName, nameReplacementChar));
if(activePrefixes[0])
{
forceUnwrap = true;
}
if(activePrefixes[1])
{
forceCollapse = true;
}
if(forceUnwrap)
{
unwrapSheet = true;
collapseSheet = false;
}
else if(forceCollapse)
{
unwrapSheet = false;
collapseSheet = true;
}
for(var j=1; j < rows; j++) //j = 1 because we don't need the keys to have a row
{
if(keyHasPrefix(values[j][0], ignorePrefix)) continue; //Skip rows with the ignore prefix
var attributeKeys = [];
var childElementKeys = [];
var innerTextKeys = [];
var attributes = [];
var childElements = [];
var innerTextElements = [];
//Separate columns into those that export as child elements or attributes
var startIndex = includeFirstColumnXml ? 0 : 1; //Exclude the first column by default since it is used as the name of the row element
for(var k=startIndex; k < columns; k++)
{
if(values[0][k] === "" || values[0][k] == null) continue; //Skip columns with empty keys
if(ignoreEmpty && values[j][k] === "") continue; //Skip empty cells if desired
if(keyHasPrefix(values[0][k], ignorePrefix)) continue; //Skip columns with the ignore prefix
//Make a note if an element name gets formatted so users know they do not have proper formatting
if(exportMessage === "" && values[0][k] !== formatXmlName(values[0][k], nameReplacementChar))
{
exportMessage = "Some keys were not properly formatted for XML and have been auto-formatted.";
exportMessageHeight = 25;
}
if((useChildElements && (attributePrefix === "" || !keyHasPrefix(values[0][k], attributePrefix)) && (innerTextPrefix === "" || !keyHasPrefix(values[0][k], innerTextPrefix))) ||
(childElementPrefix !== "" && keyHasPrefix(values[0][k], childElementPrefix)))
{
childElementKeys.push(stripPrefix(values[0][k], childElementPrefix));
childElements.push(values[j][k]);
}
else if(innerTextPrefix === "" || !keyHasPrefix(values[0][k], innerTextPrefix))
{
attributeKeys.push(stripPrefix(values[0][k], attributePrefix));
attributes.push(values[j][k]);
}
else
{
innerTextKeys.push(stripPrefix(values[0][k], innerTextPrefix));
innerTextElements.push(values[j][k]);
}
}
//Build the actual row XML
var rowXml = XmlService.createElement(formatXmlName(values[j][0], nameReplacementChar));
//Set attributes
for(var k=0; k < attributes.length; k++)
{
rowXml.setAttribute(formatXmlName(attributeKeys[k], nameReplacementChar), attributes[k]);
}
//Set child elements
for(var k=0; k < childElements.length; k++)
{
var childXml = XmlService.createElement(formatXmlName(childElementKeys[k], nameReplacementChar));
childXml.setText(childElements[k]);
rowXml.addContent(childXml);
}
//Set inner text
if(innerTextElements.length > 0)
{
var innerText = "";
for(var k=0; k < innerTextElements.length; k++)
{
innerText += innerTextElements[k];
if(k < innerTextElements.length - 1) innerText += "\n";
}
var xmlText = XmlService.createText(innerText);
rowXml.addContent(xmlText);
}
sheetXml.addContent(rowXml);
}
if(singleSheet || unwrapSheet)
{
var sheetChildren = sheetXml.getChildren();
for(var k=0; k < sheetChildren.length; k++)
{
sheetChildren[k].detach();
xmlRoot.addContent(sheetChildren[k]);
}
}
else
{
if(collapseSheet)
{
var sheetChildren = sheetXml.getChildren();
for(var k=0; k < sheetChildren.length; k++)
{
sheetChildren[k].detach();
var rowChildren = sheetChildren[k].getChildren();
for(var l=0; l < rowChildren.length; l++)
{
rowChildren[l].detach();
sheetXml.addContent(rowChildren[l]);
}
}
}
xmlRoot.addContent(sheetXml);
}
}
var xmlDoc = XmlService.createDocument(xmlRoot); //Create the final XML document for export.
var xmlFormat = minifyData ? XmlService.getRawFormat() : XmlService.getPrettyFormat(); //Select which format to export the XML as.
xmlFormat.setOmitDeclaration(true); //Remove the default XML declaration so we can build our own if desired.
if(declarationVersion !== "" && declarationEncoding !== "") xmlFormat.setEncoding(declarationEncoding); //Set the encoding method used by the XML document
var xmlRaw = xmlFormat.format(xmlDoc);
if(declarationVersion !== "")
{
var xmlDeclaration = '<?xml version="' + declarationVersion + '"';
if(declarationEncoding !== "") xmlDeclaration += ' encoding="' + declarationEncoding + '"';
if(declarationStandalone !== "") xmlDeclaration += ' standalone="' + declarationStandalone + '"';
xmlDeclaration += '?>\n';
xmlRaw = xmlDeclaration + xmlRaw;
}
exportDocument(fileName, xmlRaw, ContentService.MimeType.XML, visualize, replaceFile, exportMessage, exportMessageHeight);
}
function exportSpreadsheetJson(formatSettings)
{
//Settings
var settings = JSON.parse(formatSettings);
//File settings
var visualize = settings["visualize"];
var singleSheet = settings["singleSheet"];
var replaceFile = settings["replaceExistingFiles"];
var unwrap = settings["unwrapSingleRows"];
var collapse = settings["collapseSingleRows"] && !unwrap;
var ignoreEmpty = settings["ignoreEmptyCells"];
var ignorePrefix = settings["ignorePrefix"];
var unwrapPrefix = settings["unwrapPrefix"];
var collapsePrefix = settings["collapsePrefix"];
var customSheets = settings["targetSheets"];
var minifyData = settings["minifyData"];
//Nested Settings
var nestedElements = settings["nestedElements"];
var nestedArrayPrefix = settings["forceArrayPrefixNest"];
//JSON settings
var contentsArray = settings["exportContentsAsArray"];
var exportCellObjectJson = settings["exportCellObject"];
var exportArray = settings["exportCellArray"];
var sheetArrayJson = settings["exportSheetArray"];
var valueArray = settings["exportValueArray"];
var forceString = settings["forceString"];
var separatorChar = settings["separatorChar"];
var arrayPrefix = settings["forceArrayPrefix"];
//Sheets info
var spreadsheet = SpreadsheetApp.getActive();
var sheets = spreadsheet.getSheets();
if(customSheets != null)
{
if((isObject(customSheets) && Object.keys(customSheets).length > 0) || (!isObject(customSheets) && customSheets.length > 2))
{
var exportSheets = sheets;
sheets = new Array();
for(var i=0; i < exportSheets.length; i++)
{
if(customSheets[exportSheets[i].getName()] === 'true')
{
if(spreadsheet.getSheetByName(exportSheets[i].getName()) != null)
{
sheets.push(spreadsheet.getSheetByName(exportSheets[i].getName()));
}
}
}
}
}
var fileName = spreadsheet.getName() + (singleSheet ? (" - " + sheets[0].getName()) : "") + ".json"; //TODO: Need to strip prefixes
var sheetValues = [[]];
var rawValue = "";
var objectValue = {};
var exportMessage = "";
var exportMessageHeight = 0;
var nestedFormattingError = false;
var nestedFormattingErrorMessage = "There was a problem with nested formatting for these fields:\n";
for(var i=0; i < sheets.length; i++)
{
var range = sheets[i].getDataRange();
var values = range.getValues();
var rows = range.getNumRows();
var columns = range.getNumColumns();
var unwrapSheet = unwrap && rows <= 2; //Will this sheet be unwrapped?
var collapseSheet = collapse && rows <= 2 && !unwrapSheet; //Will this sheet be collapsed
var sheetName = sheets[i].getName();
var sheetArray = sheetArrayJson;
var sheetIsValueArray = (valueArray && columns === 1); //Is this sheet a value array?
var sheetJsonObject = {};
var sheetJsonArray = [];
var rowImplicitNames = []; //Used to keep associations with implicit key values per row.
var rowImplicitValues = [];
var hasNesting = false; //Will be set to true if any nesting occurs.