I am trying to create a table in a Doc file using Google Appsscript.
The last row should only consist of one cell:
but all I can get is this (last row aligned to the left).
I tried different things:
Help would be much appreciated. Thanks a lot!
var cells = [
['Cell 1', 'Cell 2'],
['Cell 1', 'Cell 2'],
['Cell 1', 'Cell 2'],
['Cell 1', 'Cell 2'],
["Only one Cell"]
];
var tableHeader = body.appendTable(cells);
merge()
method for merging the cells cannot be used. I'm not sure whether this is a bug or the current specification. Now, when I tested the same situation again, it seems that merge()
cannot still be used. And also, I confirmed the same result with you. I would like to expect that this issue will be resolved in the future update.But, fortunately, it has already been found that when Google Docs API is used, the table cells can be merged. So, in this answer, I would like to propose using Google Docs API for achieving your goal. When your showing script is modified, how about the following modification?
Before you use this script, please enable Docs API at Advanced Google services.
function myFunction() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var id = doc.getId();
var cells = [ // This is from your script.
['Cell 1', 'Cell 2'],
['Cell 1', 'Cell 2'],
['Cell 1', 'Cell 2'],
['Cell 1', 'Cell 2'],
["Only one Cell"]
];
var length = cells.length;
cells[length - 1].push("");
body.appendTable(cells);
doc.saveAndClose();
// Use Google Docs API.
var obj = Docs.Documents.get(id).body.content;
var table = obj.reverse().find(({ table }) => table);
var requests = [{ mergeTableCells: { tableRange: { columnSpan: 2, rowSpan: 1, tableCellLocation: { tableStartLocation: { index: table.startIndex }, rowIndex: cells.length - 1, columnIndex: 0 } } } }];
Docs.Documents.batchUpdate({ requests }, doc.getId());
}
In this modification, first, an empty value is added to the last row, and a table is created with the cells
. And, the cells of the last row are merged by Google Docs API.
In this case, in order to retrieve the location of the appended table, I used "Method: documents.get" of Google Docs API.
When this script is run, the following result is obtained.