I am trying to reproduce this table, but with a Google Docs Script.
Notice that within each cell there are different colors and different background and font styles. I can create a table like this:
var cells = [
['Row 1, Cell 1', 'Row 1, Cell 2'],
['Row 2, Cell 1', 'Row 2, Cell 2']
];
// Build a table from the array.
body.appendTable(cells);
How do I apply the formatting to each individual cell and within a specified range of text? There is this way to set the background of a cell but that sets the background of the entire cell rather than a portion of the cell.
I believe your goal as follows.
For this, how about this answer?
In this case, the following flow is used.
editAsText()
.setBackgroundColor
, setForegroundColor
, setBold
, setFontFamily
and so on.In this sample script, a table with 2 x 2 cells is appended to the document body. And, the text styles of cells "A1" and "B2" are modified.
function myFunction() {
var body = DocumentApp.getActiveDocument().getBody();
var cells = [
['This is my text', 'Row 1, Cell 2'],
['Row 2, Cell 1', 'Some more text']
];
var table = body.appendTable(cells);
// Modify the text style of the cell "A1".
table.getCell(0, 0).editAsText()
.setBackgroundColor(0, 7, "#FFFF00")
.setForegroundColor(5, 9, "#FF0000")
.setBackgroundColor(8, 14, "#00BFFF")
.setBold(8, 14, true);
// Modify the text style of the cell "B2".
table.getCell(1, 1).editAsText()
.setFontFamily(5, 13, "IMPACT")
.setBackgroundColor(5, 13, "#00BFFF")
.setBold(5, 13, true);
}
setBackgroundColor(startOffset, endOffsetInclusive, color)
. Ref When the text style of This is
is modified, please use setBackgroundColor(0, 7, "#FFFF00")
.When above sample script is run, the following result can be obtained.