Search code examples
javascriptgoogle-apps-scriptgoogle-docs

Modify a table from script in Google Docs


I have a Google Doc containing one table. I'm trying to write a script that appends a number of empty rows to a table, how can I do that?

I've tried with the following function:

function insertRows2() {
  var NUMBER_OF_ROWS = 40;

  var body = DocumentApp.getActiveDocument().getBody(),
      searchElement = body.findElement(DocumentApp.ElementType.TABLE),
      element = searchElement.getElement(),
      table = element.asTable();

  Logger.log('num rows: ' + table.getNumRows());

  for (var i = 0; i < NUMBER_OF_ROWS; i++) {
    table.appendTableRow();
  }

  Logger.log('num rows: ' + table.getNumRows());
}

The output is:

[14-11-25 15:02:26:275 CET] num rows: 1077
[14-11-25 15:02:26:353 CET] num rows: 1117

But I don't see the newly created rows in the document. If I manually insert a row form the UI, and then re-execute the script I get:

[14-11-25 15:04:24:317 CET] num rows: 1118
[14-11-25 15:04:24:400 CET] num rows: 1158

So it seems that the code is actually working on the right table, but I don't see the new rows in the document itself.

The log says 1158 rows but the document actually just has ~30 rows


Solution

  • By calling table.appendTableRow(), you are appending empty rows - and empty isn't the same as blank.

    In contrast, the UI is adding blank rows, which have child tableCells. Any visible content in a row ends up contained in a tableCell; so by adding at least one of those to your row, you should end up with a visible row.

    Try table.appendTableRow().appendTableCell(); instead.