appendRangeAsDocTable(body, values, opts) appends a 2D array onto a Google Doc as a real table. The first row is styled as a header, and you can pass column widths in points.
When to use
- Dropping a sheet range into a weekly Doc report
- A summary table at the end of a letter or invoice Doc
- Any script that should produce a Doc table, not a tab-separated paste
How to use this snippet
/**
* Append a 2D array as a table on a Doc body.
* Row 0 is the header (bold, dark background, light text).
* opts.columnWidths is an array of widths in points.
*
* @param {GoogleAppsScript.Document.Body} body
* @param {Array<Array<*>>} values
* @param {{headerBackground?: string, headerColor?: string, columnWidths?: number[]}} [opts]
* @return {GoogleAppsScript.Document.Table}
*/
function appendRangeAsDocTable(body, values, opts) {
opts = opts || {};
if (!values || !values.length || !values[0] || !values[0].length) {
throw new Error('appendRangeAsDocTable: values must be a non-empty 2D array');
}
var cols = values[0].length;
var cells = values.map(function (r) {
var row = [];
for (var c = 0; c < cols; c++) row.push(r[c] == null ? '' : String(r[c]));
return row;
});
var table = body.appendTable(cells);
var headerBg = opts.headerBackground || '#11313A';
var headerFg = opts.headerColor || '#FFFFFF';
var header = table.getRow(0);
for (var c = 0; c < cols; c++) {
var cell = header.getCell(c);
cell.setBackgroundColor(headerBg);
var text = cell.editAsText();
text.setForegroundColor(headerFg);
text.setBold(true);
}
var widths = opts.columnWidths || [];
for (var w = 0; w < widths.length && w < cols; w++) {
if (widths[w] != null) table.setColumnWidth(w, widths[w]);
}
return table;
}
Example
function dropWeeklyTable() {
var values = SpreadsheetApp.getActive().getSheetByName('Summary').getDataRange().getDisplayValues();
var doc = DocumentApp.openById('DOC_ID');
appendRangeAsDocTable(doc.getBody(), values, { columnWidths: [180, 90, 90] });
doc.saveAndClose();
}
Notes
- Pass
getDisplayValues()if the source is a sheet, so dates and currency look the way they do in the grid. - Ragged rows are padded to the first row's column count. Empty input throws.
- This appends at the end of the body. Add a heading yourself first if the table should sit under a title.
- For filling
{{placeholders}}in a template, that is a different job: Fill Doc Template.
Happy Coding!
