Description:
Stack Overflow user mhawksey recently did some fantastic optimization of my code, and in doing so, introduced me to super efficient array p
REMARK: The OP did a huge change from revision 1 to revision 3. Following is the content taken from the source of the revision 1.
Is it possible to push text to a spreadsheet with formatting such as .setFontColor, .setBackgroundColor or .setBorder? I've been monkeying around with code but never get an error message. It just doesn't do anything. I'm working with something like this:
if (cell === "This should be red") { var redCell = (data[(row)][0]).setFontColor('red'); array.push([redCell]); }
Following is my answer to the revision 1.
To copy the value and format from one cell or range to another use copyTo(destination).
From the above link
// The code below will copy the first 5 columns over to the 6th column.
var sheet = SpreadsheetApp.getActiveSheet();
var rangeToCopy = sheet.getRange(1, 1, sheet.getMaxRows(), 5);
rangeToCopy.copyTo(sheet.getRange(1, 6));
}
You can use all the various spreadsheet methods to get and set colors, font sizes, font weights, etc. to and from distinct arrays but you can not mix these "attributes" in one single item. See the doc here.
Or even handier, in your script editor write a script that defines a range and play with the auto complete to see everything you can do with it...
(control+space keys)
You should create a second array that holds all the background colors of your range and fill it according to your needs. In the code below I build the array in parrallels with your output array, not very elegantly but rather systematically to show how it works.
Note that null value means "no background color" while #0F0 is the hexadecimal code for green but you can also use the 'green' string if you prefer...
...
var output = [];
var backGrounds=[]
//loop through all cells in column A
for (row = 0; row < lastRow; row++) {
var cellValue = data[row][0];
var dash = false;
if (typeof cellValue === 'string') {
dash = cellValue.substring(0, 1);
//if a number copy to our output array
} else {
output.push([cellValue]);
backGrounds.push([null]);
}
//if -dash
if (dash === "-") {
//build first + last name
var name = (data[(row+1)][0]+" "+data[(row+2)][0]).trim();
//add row for the -state (e.g. -MI)
output.push([cellValue]);
backGrounds.push([null]);
output.push([name]);
backGrounds.push([null]);
output.push(["Order complete"]);
backGrounds.push(['#0F0']);
//add a blank row
output.push([""]);
backGrounds.push([null]);
//jump an extra row to speed things up
row++;
}
}
s.getRange(1, 1, output.length).setBackgrounds(backGrounds);
...