-
Notifications
You must be signed in to change notification settings - Fork 61
/
book_code.gs
3402 lines (3349 loc) · 96.3 KB
/
book_code.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
/*
All the code examples from "Google Spreadsheet Programming"
Author: Michael Maguire
*/
// Chapter 2
function sayHelloBrowser() {
// Declare a string literal variable.
var greeting = 'Hello world!';
// Display a message dialog with the greeting
//(visible from the containing spreadsheet).
Browser.msgBox(greeting);
}
function helloDocument() {
var greeting = 'Hello world!';
// Create DocumentApp instance.
var doc =
DocumentApp.create('test_DocumentApp');
// Write the greeting to a Google document.
doc.setText(greeting);
// Close the newly created document
doc.saveAndClose();
}
function helloLogger() {
var greeting = 'Hello world!';
//Write the greeting to a logging window.
// This is visible from the script editor
// window menu "View->Logs...".
Logger.log(greeting);
}
function helloSpreadsheet() {
var greeting = 'Hello world!',
sheet = SpreadsheetApp.getActiveSheet();
// Post the greeting variable value to cell A1
// of the active sheet in the containing
// spreadsheet.
sheet.getRange('A1').setValue(greeting);
// Using the LanguageApp write the
// greeting to cell:
// A2 in Spanish,
// cell A3 in German,
// and cell A4 in French.
sheet.getRange('A2')
.setValue(LanguageApp.translate(
greeting, 'en', 'es'));
sheet.getRange('A3')
.setValue(LanguageApp.translate(
greeting, 'en', 'de'));
sheet.getRange('A4')
.setValue(LanguageApp.translate(
greeting, 'en', 'fr'));
}
// Chapter 3
// Cannot be called as a UDF.
function setRangeFontBold (rangeAddress) {
var sheet =
SpreadsheetApp.getActiveSheet();
sheet.getRange(rangeAddress)
.setFontWeight('bold');
}
// Call "setRangeFontBold()" from editor.
function call_setCellFontBold () {
var rangeAddress = Browser.inputBox(
'Set Range Font Bold',
'Provide a range address',
Browser.Buttons.OK_CANCEL);
if (rangeAddress) {
setRangeFontBold(rangeAddress);
}
}
// Given the standard deviation and the mean,
// return the relative standard deviation.
function RSD (stdev, mean) {
if (!(typeof stdev === 'number' &&
typeof mean === 'number')) {
throw {'name': 'TypeError',
'message':
'Function "RSD()" requires ' +
'two numeric arguments'};
}
return (100 * (stdev/mean)).toFixed(2)*1;
}
// Given a temperature value in Celsius
// return the temperature in Fahrenheit.
function celsiusToFahrenheit (celsius) {
if (typeof celsius !== 'number') {
throw {
'name': 'TypeError',
'message': 'Function requires ' +
'a single number argument'};
}
return ((celsius * 9) / 5) + 32;
}
// Given a temperature in Fahrenheit,
// return the temperature in Celsius.
function fahrenheitToCelsius(fahrenheit) {
if (typeof fahrenheit !== 'number') {
throw {
'name': 'TypeError',
'message': 'Function requires ' +
' a single number argument'};
}
return ( fahrenheit - 32 ) * 5/9;
}
// Given the radius, return the
// area.
// Throw an error if the radius is
// negative.
function areaOfCircle (radius) {
if (typeof radius !== 'number'){
throw {
'name': 'TypeError',
'message': 'Function requires ' +
'a single numeric argument'};
}
if (radius < 0) {
throw {
'name': 'ValueError',
'message': 'Radius myst ' +
' be non-negative'};
}
return Math.PI * (radius * radius);
}
function test_intervalInDays() {
var date1 = new Date(),
date2 = new Date(1972, 7, 17);
Logger.log(intervalInDays(date1, date2));
}
// Write String methods to the logger.
function printStringMethods() {
var strMethods =
Object.getOwnPropertyNames(
String.prototype);
Logger.log('String has ' +
strMethods.length +
' properties.');
Logger.log(strMethods.sort().join('\n'));
}
// Reverse the alphabet.
function test_reverseString () {
var str = 'abcdefghijklmnopqrstuvwxyz';
Logger.log(reverseString(str));
}
// Return a string with the characters
// of the input string reversed.
function reverseString (str) {
var strReversed = '',
lastCharIndex = str.length - 1,
i;
if (typeof str !== 'string') {
throw {
'name': 'TypeError',
'message': 'Function requires a ' +
' single string argument.'};
}
for (i = lastCharIndex; i >= 0; i -= 1) {
strReversed += str[i];
}
return strReversed;
}
// Return a integer between
// 1 and 6 inclusive.
function throwDie () {
return 1 + Math.floor(Math.random() * 6);
}
// Concatenate cell values from
// an input range.
// Single quotes around concatenated
// elements are optional.
function concatRng(inputFromRng, concatStr,
addSingleQuotes) {
var cellValues;
if (addSingleQuotes) {
cellValues =
inputFromRng.map(
function (element) {
return "'" + element + "'";
});
return cellValues.join(concatStr);
}
return inputFromRng.join(concatStr);
}
// Print stockInfo object property
// names to the logger.
function printFinanceAppKeys() {
stockSymbol = 'GOOG';
Logger.log(Object.keys(
FinanceApp.getStockInfo(
stockSymbol))
.sort()
.join('\n'));
}
// Given a stock symbol, return the
// stock price (NYSE).
function getStockPrice(stockSymbol) {
return FinanceApp
.getStockInfo(stockSymbol)['price'];
}
// Given a stock symbol, return the
// full stock name.
function getStockName(stockSymbol) {
return FinanceApp
.getStockInfo(stockSymbol)['name'];
}
// Chapter 4
// Function to demonstrate the Spreadsheet
// object hierarchy.
// All the variables are gathered in a
// JavaScript array.
// At each iteration of the for loop the
// "toString()" method
// is called for each variable and its
// output is printed to the log.
function showGoogleSpreadsheetHierarchy() {
var ss = SpreadsheetApp.getActiveSpreadsheet(),
sh = ss.getActiveSheet(),
rng = ss.getRange('A1:C10'),
innerRng = rng.getCell(3, 3),
innerRngAddress = innerRng.getA1Notation(),
column = innerRngAddress.slice(0,1),
googleObjects = [ss, sh, rng, innerRng,
innerRngAddress, column],
i;
for (i = 0; i < googleObjects.length; i += 1) {
Logger.log(googleObjects[i].toString());
}
}
// Print the column letter of the third row and
// third column of the range "A1:C10"
// of the active sheet in the active
// spreadsheet.
// This is for demonstration purposes only!
function getColumnLetter () {
Logger.log(
SpreadsheetApp.getActiveSpreadsheet()
.getActiveSheet().getRange('A1:C10')
.getCell(3, 3).getA1Notation()
.slice(0,1));
}
// Extract an array of all the property names
// defined for Spreadsheet and write them to
// column A of the active sheet in the active
// spreadsheet.
function testSpreadsheet () {
var ss =
SpreadsheetApp.getActiveSpreadsheet(),
sh = ss.getActiveSheet(),
i,
spreadsheetProperties = [],
outputRngStart = sh.getRange('A2');
sh.getRange('A1')
.setValue('spreadsheet_properties');
sh.getRange('A1')
.setFontWeight('bold');
spreadsheetProperties =
Object.keys(ss).sort();
for (i = 0;
i < spreadsheetProperties.length;
i += 1) {
outputRngStart.offset(i, 0)
.setValue(spreadsheetProperties[i]);
}
}
// Extract, an array of properties from a
// Sheet object.
// Sort the array alphabetically using the
// Array sort() method.
// Use the Array join() method to a create
// a string of all the Sheet properties
// separated by a new line.
function printSheetProperties () {
var ss =
SpreadsheetApp.getActiveSpreadsheet(),
sh = ss.getActiveSheet();
Logger.log(Object.keys(sh)
.sort().join('\n'));
}
// Call function listSheets() passing it the
// Spreadsheet object for the active
// spreadsheet.
// The try - catch construct handles the
// error thrown by listSheets() if the given
// argument is absent or something
// other than a Spreadsheet object.
function test_listSheets () {
var ss =
SpreadsheetApp.getActiveSpreadsheet();
try {
listSheets(ss);
} catch (error) {
Logger.log(error.message);
}
}
// Given a Spreadsheet object,
// print the names of its sheets
// to the logger.
// Throw an error if the argument
// is missing or if it is not
// of type Spreadsheet.
function listSheets (spreadsheet) {
var sheets,
i;
if (spreadsheet.toString()
!== 'Spreadsheet') {
throw {
'name': 'TypeError',
'message': 'Function "listSheets()" '
'requires ' +
'a single argument of ' +
'type "Spreadsheet".'};
}
sheets = spreadsheet.getSheets();
for (i = 0;
i < sheets.length; i += 1) {
Logger.log(sheets[i].getName());
}
}
// Create a Spreadsheet object and call
// "sheetExists()" for an array of sheet
// names to see if they exist in
// the given spreadsheet.
// Print the output to the log.
function test_sheetExists () {
var ss =
SpreadsheetApp.getActiveSpreadsheet(),
sheetNames = ['Sheet1',
'sheet1',
'Sheet2',
'SheetX'],
i;
for (i = 0;
i < sheetNames.length;
i +=1) {
Logger.log('Sheet Name ' +
sheetNames[i] +
' exists: ' +
sheetExists(ss,
sheetNames[i]));
}
}
// Given a Spreadsheet object and a sheet name,
// check for two arguments of the correct type.
// Return "true" if the given sheet name exists
// in the given Spreadsheet,
// else return "false".
function sheetExists(spreadsheet, sheetName) {
var sheet;
if (spreadsheet.toString() !==
'Spreadsheet') {
throw {
'name': 'TypeError',
'message': 'Function "sheetExists()" ' +
'first argument for ' +
'"spreadsheet" is ' +
'not type "Spreadsheet".'};
}
if (typeof sheetName !== 'string') {
throw {
'name': 'TypeError',
'message': 'Function "sheetExists()" ' +
'second argument ' +
'for "sheetName" ' +
'is not type string.'};
}
if (spreadsheet.getSheetByName(sheetName)) {
return true;
} else {
return false;
}
}
// Copy the first sheet of the active
// spreadsheet to a newly created
// spreadsheet.
function copySheetToSpreadsheet () {
var ssSource =
SpreadsheetApp.getActiveSpreadsheet(),
ssTarget =
SpreadsheetApp.create(
'CopySheetTest'),
sourceSpreadsheetName =
ssSource.getName(),
targetSpreadsheetName =
ssTarget.getName();
Logger.log(
'Copying the first sheet from ' +
sourceSpreadsheetName +
' to ' + targetSpreadsheetName);
// [0] extracts the first Sheet object
// from the array created by
// method call "getSheets()"
ssSource.getSheets()[0].copyTo(ssTarget);
}
// Create a Sheet object and pass it
// as an argument to getSheetSummary().
// Print the return value to the log.
function test_getSheetSummary () {
var sheet = SpreadsheetApp
.getActiveSpreadsheet()
.getSheets()[0];
Logger.log(getSheetSummary(sheet));
}
// Given a Sheet object as an argument,
// use Sheet methods to extract
// information about it.
// Collect this information into an object
// literal and return the object literal.
function getSheetSummary (sheet) {
var sheetReport = {};
if (sheet.toString() !== 'Sheet') {
throw {
'name': 'TypeError',
'message': 'Function "getSheetReport()" ' +
'requires a single ' +
'argument of type "Sheet".'};
}
sheetReport['Sheet Name'] =
sheet.getName();
sheetReport['Used Row Count'] =
sheet.getLastRow();
sheetReport['Used Column count'] =
sheet.getLastColumn();
sheetReport['Used Range Address'] =
'A1:' +
sheet.getRange(sheet.getLastRow(),
sheet.getLastColumn()).getA1Notation();
return sheetReport;
}
// Chapter 5
// Select a number of cells in a spreadsheet and
// then execute the following function.
// The address of the selected range, that is the
// active range, is written to the log.
function activeRangeFromSpreadsheetApp () {
var activeRange =
SpreadsheetApp.getActiveRange();
Logger.log(activeRange.getA1Notation());
}
// Get the active cell and print its containing
// sheet name and address to the log.
// Try re-running after adding a new sheet
// and selecting a cell at random.
function activeCellFromSheet () {
var activeSpreadsheet =
SpreadsheetApp.getActiveSpreadsheet(),
activeCell =
activeSpreadsheet.getActiveCell(),
activeCellSheetName =
activeCell.getSheet().getSheetName(),
activeCellAddress =
activeCell.getA1Notation();
Logger.log('The active cell is in sheet: ' +
activeCellSheetName);
Logger.log('The active cell address is: ' +
activeCellAddress);
}
// Print Range object properties
// (all are methods) to log.
function printRangeMethods () {
var rng =
SpreadsheetApp.getActiveRange();
Logger.log(Object.keys(rng)
.sort().join('\n'));
}
// Creating a Range object using two different
// overloaded versions of the Sheet
// "getRange()" method.
// "getSheets()[0]" gets the first sheet of the
// array of Sheet objects returned by
// "getSheets()".
// Both calls to "getRange()" return a Range
// object representing the same range address
// (A1:B10).
function getRangeObject () {
var ss =
SpreadsheetApp.getActiveSpreadsheet(),
sh = ss.getSheets()[0],
rngByAddress = sh.getRange('A1:B10'),
rngByRowColNums =
sh.getRange(1, 1, 10, 2);
Logger.log(rngByAddress.getA1Notation());
Logger.log(
rngByRowColNums.getA1Notation());
}
// Set a number of properties for a range.
// Add a new sheet.
// Set various properties for the cell
// A1 of the new sheet.
function setRangeA1Properties() {
var ss =
SpreadsheetApp.getActiveSpreadsheet(),
newSheet,
rngA1;
newSheet = ss.insertSheet();
rngA1 = newSheet.getRange('A1');
rngA1.setComment(
'Hold The date returned by spreadsheet '
+ ' function "TODAY()"');
rngA1.setFormula('=TODAY()');
rngA1.setBackgroundColor('black');
rngA1.setFontColor('white');
rngA1.setFontWeight('bold');
}
// Demonstrate get methods for 'Range'
// properties.
// Assumes function "setRangeA1Properties()
// has been run.
// Prints the properties to the log.
// Demo purposes only!
function printA1PropertiesToLog () {
var rngA1 =
SpreadsheetApp.getActiveSpreadsheet()
.getSheetByName('RangeTest').getRange('A1');
Logger.log(rngA1.getComment());
Logger.log(rngA1.getFormula());
Logger.log(rngA1.getBackground());
Logger.log(rngA1.getFontColor());
Logger.log(rngA1.getFontWeight());
}
// Starting with cell C10 of the active sheet,
// add comments to each of its adjoining cells
// stating the row and column offsets needed
// to reference the commented cell
// from cell C10.
function rangeOffsetDemo () {
var rng =
SpreadsheetApp.getActiveSheet()
.getRange('C10');
rng.setBackground('red');
rng.setValue('Method offset()');
rng.offset(-1,-1)
.setComment('Offset -1, -1 from cell '
+ rng.getA1Notation());
rng.offset(-1,0)
.setComment('Offset -1, 0 from cell '
+ rng.getA1Notation());
rng.offset(-1,1)
.setComment('Offset -1, 1 from cell '
+ rng.getA1Notation());
rng.offset(0,1)
.setComment('Offset 0, 1 from cell '
+ rng.getA1Notation());
rng.offset(1,0)
.setComment('Offset 1, 0 from cell '
+ rng.getA1Notation());
rng.offset(0,1)
.setComment('Offset 0, 1 from cell '
+ rng.getA1Notation());
rng.offset(1,1)
.setComment('Offset 1, 1 from cell '
+ rng.getA1Notation());
rng.offset(0,-1)
.setComment('Offset 0, -1 from cell '
+ rng.getA1Notation());
rng.offset(1,-1)
.setComment('Offset -1, -1 from cell '
+ rng.getA1Notation());
}
// Passing a deliberately "bad" argument to the
// Range offset() method.
// The row offset argument is -1 but
// there is no row above row 1
// (cell A1's row).
// Google Apps Script gives error:
// "It looks like someone else
// already deleted this cell."
function offsetError () {
var rng =
SpreadsheetApp.getActiveSpreadsheet()
.getActiveSheet()
.getRange('A1');
rng.offset(-1,0)
.setValue('bad offset argument.');
}
function offsetError () {
var rng =
SpreadsheetApp.getActiveSpreadsheet()
.getActiveSheet().getRange('A1');
Logger.log(rng.offset(-1,0).getValue());
}
// See the Sheet method getDataRange() in action.
// Print the range address of the used range for
// a sheet to the log.
function getDataRange () {
var ss =
SpreadsheetApp.getActiveSpreadsheet(),
sheetName = 'english_premier_league',
sh = ss.getSheetByName(sheetName),
dataRange = sh.getDataRange();
Logger.log(dataRange.getA1Notation());
}
// Read the entire data range of a sheet
// into a JavaScript array.
// Uses the JavaScript Array.isArray()
// method twice to verify that method
// getValues()returns an array-of-arrays.
// Print the number of array elements
// corresponding to the number of data
// range rows.
// Extract and print the first 10
// elements of the array using the
// array slice() method.
function dataRangeToArray () {
var ss =
SpreadsheetApp.getActiveSpreadsheet(),
sheetName = 'english_premier_league',
sh = ss.getSheetByName(sheetName),
dataRange = sh.getDataRange(),
dataRangeValues = dataRange.getValues();
Logger.log(Array.isArray(dataRangeValues));
Logger.log(Array.isArray(dataRangeValues[0]));
Logger.log(dataRangeValues.length);
Logger.log(dataRangeValues.slice(0, 10));
}
// Loop over the array returned by
// getRange() and a CSV-type output
// to the log using array join() method.
function loopOverArray () {
var ss =
SpreadsheetApp.getActiveSpreadsheet(),
sheetName = 'english_premier_league',
sh = ss.getSheetByName(sheetName),
dataRange = sh.getDataRange(),
dataRangeValues =
dataRange.getValues(),
i;
for ( i = 0;
i < dataRangeValues.length;
i += 1 ) {
Logger.log(
dataRangeValues[i].join(','));
}
}
// In production code, this function would be
// re-factored into smaller functions.
// Read the data range into a JavaScript array.
// Remove and store the header line using the
// array shift() method.
// Use the array filter() method with an anonymous
// function as a callback to implement the
// filtering logic.
// Determine the element count of the
// filter() output array.
// Add a new sheet and store a reference to it.
// Create a Range object from the new
// Sheet objectusing the getRange() method.
// The four arguments given to getRange() are:
// (1) first column, (2) first row,
// (3) last row, and (4) last column.
// This creates a range corresponding to
// range address "A1:C5".
// Write the values of the filtered array to the
// newly created range.
function writeFilteredArrayToRange () {
var ss =
SpreadsheetApp.getActiveSpreadsheet(),
sheetName = 'english_premier_league',
sh = ss.getSheetByName(sheetName),
dataRange = sh.getDataRange(),
dataRangeValues = dataRange.getValues(),
filteredArray,
header = dataRangeValues.shift(),
filteredArray,
filteredArrayColCount = 3,
filteredArrayRowCount,
newSheet,
outputRange;
filteredArray = dataRangeValues.filter(
function (innerArray) {
if (innerArray[2] >= 40) {
return innerArray;
}});
filteredArray.unshift(header);
filteredArrayRowCount = filteredArray.length;
newSheet = ss.insertSheet();
outputRange = newSheet
.getRange(1,
1,
filteredArrayRowCount,
filteredArrayColCount);
outputRange.setValues(filteredArray);
}
function setRangeName () {
var ss =
SpreadsheetApp.getActiveSpreadsheet(),
sh = ss.getActiveSheet(),
rng = sh.getRange('A1:B10'),
rngName 'MyData';
ss.setNamedRange(rngName, rng);
}
// Create a range object using the
// getDataRange() method.
// Pass the range and a colour name
// to function "setAlternateRowsColor()".
// Try changing the 'color' variable to
// something like:
// 'red', 'green', 'yellow', 'gray', etc.
function call_setAlternateRowsColor () {
var ss =
SpreadsheetApp.getActiveSpreadsheet(),
sheetName = 'english_premier_league',
sh = ss.getSheetByName(sheetName),
dataRange = sh.getDataRange(),
color = 'grey';
setAlternateRowsColor(dataRange, color);
}
// Set every second row in a given range to
// the given colour.
// Check for two arguments:
// 1: Range, 2: string for colour.
// Throw a type error if either argument
// is missing or of the wrong type.
// Use the Range offset() to loop
// over the range rows.
// the for loop counter starts at 0.
// It is tested in each iteration with the
// modulus operator (%).
// If i is an odd number, the if condition
// evaluates to true and the colour
// change is applied.
// WARNING: If a non-existent colour is given,
// then the "color" is set to undefined
(no color). NO error is thrown!
function setAlternateRowsColor (range,
color) {
if (range.toString()
!== 'Range') {
throw {'name': 'TypeError',
'message':
'The first argument to ' +
'"setAlternateRowsColor()" ' +
' must be type Range'};
}
if (typeof color !== 'string') {
throw {'name': 'TypeError',
'message':
'The second argument to ' +
' "setAlternateRowsColor()" ' +
' must be a string for a color,' +
' e.g. "red"'};
}
var i,
startCell = range.getCell(1,1),
columnCount = range.getLastColumn(),
lastRow = range.getLastRow();
for (i = 0; i < lastRow; i += 1) {
if (i % 2) {
startCell.offset(i, 0, 1, columnCount)
.setBackgroundColor(color);
}
}
}
// Test function for
// "deleteLeadingTrailingSpaces()".
// Creates a Range object and passes
// it to this function.
function call_deleteLeadingTrailingSpaces() {
var ss =
SpreadsheetApp.getActiveSpreadsheet(),
sheetName = 'english_premier_league',
sh = ss.getSheetByName(sheetName),
dataRange = sh.getDataRange();
deleteLeadingTrailingSpaces(dataRange);
}
// Process each cell in the given range.
// If the cell is of type text
// (typeof === 'string') then
// remove leading and trailing white space.
// Else ignore it.
// Code note: The Range getCell() method
// takes two 1-based indexes
// (row and column).
// This is in contrast to the offset() method.
// rng.getCell(0,0) will throw an error!
function deleteLeadingTrailingSpaces(range) {
if (range.toString() !== 'Range') {
throw {'name': 'TypeError',
'message':
'Argument to ' +
'"deleteLeadingTrailingSpaces()" ' +
'must be type Range'};
}
var i,
j,
lastCol = range.getLastColumn(),
lastRow = range.getLastRow(),
cell,
cellValue;
for (i = 1; i <= lastRow; i += 1) {
for (j = 1; j <= lastCol; j += 1) {
cell = range.getCell(i,j);
cellValue = cell.getValue();
if (typeof cellValue === 'string') {
cellValue = cellValue.trim();
cell.setValue(cellValue);
}
}
}
}
// Create a Sheet object for the active sheet.
// Pass the sheet object to
// "getAllDataRangeFormulas()"
// Create an array of the keys in the returned
// object in default "sort()".
// Loop over the array of sorted keys and
// extract the values they keys map to.
// Write the output to the log.
function call_getAllDataRangeFormulas() {
var ss =
SpreadsheetApp.getActiveSpreadsheet(),
sheet = ss.getActiveSheet(),
sheetFormulas = getAllDataRangeFormulas(sheet),
formulaLocations =
Object.keys(sheetFormulas).sort(),
formulaCount = formulaLocations.length,
i;
for (i = 0; i < formulaCount; i += 1) {
Logger.log(formulaLocations[i] +
' contains ' +
sheetFormulas[formulaLocations[i]]);
}
}
// Take a Sheet object as an argument,
// throw an error if the given argument
// is of the wrong type.
// Return an object literal where formula
// locations map to formulas for all formulas
// in the input sheet data range.
// Loop through every cell in the data range.
// If a cell has a formula,
// store that cells location as
// the key and its formula as the value
// in the object literal.
// Return the populated object literal.
function getAllDataRangeFormulas(sheet) {
if (sheet.toString() !== 'Sheet') {
throw {'name': 'TypeError',
'message':
'Function "getAllDataRangeFormulas()" ' +
' expects a single argument of ' +
' type Sheet.'};
}
var dataRange = sheet.getDataRange(),
i,
j,
lastCol = dataRange.getLastColumn(),
lastRow = dataRange.getLastRow(),
cell,
cellFormula,
formulasLocations = {},
sheetName = sheet.getSheetName(),
cellAddress;
for (i = 1; i <= lastRow; i += 1) {
for (j = 1; j <= lastCol; j += 1) {
cell = dataRange.getCell(i,j);
cellFormula = cell.getFormula();
if (cellFormula) {
cellAddress = sheetName + '!' +
cell.getA1Notation();
formulasLocations[cellAddress] =
cellFormula;
}
}
}
return formulasLocations;
}
// Call copyColumns() function passing it:
// 1: The active sheet
// 2: A newly inserted sheet
// 3: An array of column indexes to copy
// to the new sheet
// The output in the newly inserted sheet
// contains the columns for the indexes
// given in the array in the
// order specified in the array.
function call_copyColumns() {
var ss =
SpreadsheetApp.getActiveSpreadsheet(),
inputSheet = ss.getActiveSheet(),
outputSheet = ss.insertSheet(),
columnIndexes = [4,3,2,1];
copyColumns(inputSheet,
outputSheet,
columnIndexes);
}
// Given an input sheet, an output sheet,
// and an array:
// Use the numeric column indexes in
// the array to copy those columns from
// the input sheet to the output sheet.
// The function checks its input arguments
// and throws an error
// if they are not Sheet, Sheet, Array.
// The array is expected to be an array of
// integers but it does
// not check the array element types
function copyColumns(inputSheet,
outputSheet,
columnIndexes) {
if (! (inputSheet.toString() ===
'Sheet'
&&
outputSheet.toString() === 'Sheet') ) {
throw {'name': 'TypeError',
'message': 'Function ' + '
"copyColumns()": ' +
'First two arguments must ' +
' be Sheet objects'};
}
if (! Array.isArray(columnIndexes)) {
throw {'name': 'TypeError',
'message': 'Function ' +
'"copyColumns()": ' +
'Third argument has to be ' +
' an array of indexes'};
}
var dataRangeRowCount =
inputSheet.getDataRange()
.getNumRows(),
columnsToCopyCount =
columnIndexes.length,
i,
columnIndexesCount,
valuesToCopy = [];
for (i = 0;
i < columnsToCopyCount;
i += 1) {
valuesToCopy =
inputSheet
.getRange(1,
columnIndexes[i],
dataRangeRowCount,
1).getValues();
outputSheet
.getRange(1,
i+1,
dataRangeRowCount,
1).setValues(valuesToCopy);
}
}
// Chapter 6
// Test connection to a MySQ
// cloud instance created earlier.
// Check log for output.
function connectMySqlCloud() {
var connStr =
'jdbc:google:rdbms://' +
'elwarbito:chapter6/contacts',
conn;
try {
conn =
Jdbc.getCloudSqlConnection(connStr);
Logger.log('Connection OK!');
} catch (err) {
Logger.log(err);
throw err;
} finally {
if (conn) {
conn.close();
}
}
}
// Execute a CREATE TABLE DDL statement for a
// database named "contacts".
function createTable() {
var connStr =
'jdbc:google:rdbms://' +
'elwarbito:chapter6/contacts',
conn,
stmt,
ddl;
ddl = 'CREATE TABLE person(' +
' person_id MEDIUMINT ' +
'AUTO_INCREMENT' +
' NOT NULL PRIMARY KEY,' +
' first_name VARCHAR(100) NOT NULL,' +
' last_name VARCHAR(100) NOT NULL,' +
' date_of_birth DATE,' +
' height_cm SMALLINT)';
try {
conn =
Jdbc.getCloudSqlConnection(connStr);
stmt = conn.createStatement();
stmt.execute(ddl);
Logger.log('Table created!');