I successfully merged cells in a Google Docs table using the Google Docs API through a Google Apps Script function (in JavaScript). Below are the steps my function follows:
- Iterate over the document's content.
- Locate a specific table based on an identifier above it, labeled
table_marker
. - Create the
updateRequests
variable. - Execute this variable using
batchUpdate
.
As a result, cells between startCell
and endCell
are merged.
function mergeTableCells(docId, tableMarker, startCell, endCell) { let documentContent = Docs.Documents.get(docId).body.content;
for (var index = 0; index < documentContent.length; index++) {
if (documentContent[index].table != null) {
let marker = documentContent[index - 1].paragraph.elements[0].textRun.content.trim();
if (marker === tableMarker) {
tableIndex = documentContent[index].startIndex;
break; // exit loop
}
}
}
let updateRequests = [{
mergeTableCells: {
tableRange: {
tableCellLocation: {
tableStartLocation: {index: tableIndex},
rowIndex: startCell[0],
columnIndex: startCell[1]
},
columnSpan: endCell[1] - startCell[1] + 1,
rowSpan: endCell[0] - startCell[0] + 1
}
}
}];
Logger.log(updateRequests);
return updateRequests;
}
When I invoke this function from another function, it operates flawlessly:
function mainFunction1() {
let activeDocId = DocumentApp.getActiveDocument().getId();
mergeTableCells(activeDocId, '<>', [1, 2], [2, 3]);
}
Currently, I am attempting to modify the last line within the function to replace Docs.Documents.batchUpdate({ requests }, docId);
with return(updateRequests);
and subsequently invoke it from a main function as demonstrated below:
function mainFunction2() {
let activeDocId = DocumentApp.getActiveDocument().getId();
let requestsToUpdate = mergeTableCells(activeDocId, '<>', [1, 2], [2, 3]);
Logger.log(requestsToUpdate);
Docs.Documents.batchUpdate({ requests: requestsToUpdate }, activeDocId);
}
The log output for updateRequests
matches what is returned by requestsToUpdate
, yet I encounter the following error when executing mainFunction2
: GoogleJsonResponseException: API call to docs.documents.batchUpdate failed with error: Invalid JSON payload received. Unknown name "requestsToUpdate": Cannot find field. What steps should I take to correctly pass requestsToUpdate
to batchUpdate
?