google-apps-scriptgoogle-docs

How can I merge two cells for a specific table row only?


I am trying to create a table in a Doc file using Google Appsscript. The last row should only consist of one cell: enter image description here

but all I can get is this (last row aligned to the left).

enter image description here

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);

Solution

  • Issue and workaround:

    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?

    Modified script:

    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());
    }
    

    Testing:

    When this script is run, the following result is obtained.

    enter image description here

    References: