Search code examples
google-apps-scriptgoogle-docs

Use Google Script to Edit and Delete Tables in Document


Immediately below is a function that creates a sample document and inserts three tables into it. The three existing tables appear in the log as [Table, Table, Table], with a correct count of 3. How do I "access" or "select" these tables for editing? I'd like to receive from someone the code that's needed to add a row at the end of table 1, and then the code to delete table 2. If I understand that, I think I'll have what I need.

function create_edit_delete_table() {

// Create sample table and get id
var docId = DocumentApp.create('SAMPLE_DOCUMENT').getId();

// Get doc body
var body = DocumentApp.openById(docId).getBody();

// Create a two-dimensional array containing the cell contents.
var cells = [
  ['Row 1, Cell 1', 'Row 1, Cell 2'],
  ['Row 2, Cell 1', 'Row 2, Cell 2']
];

// Build three tables from the array and insert into document.
body.appendTable(cells);
body.appendTable(cells);
body.appendTable(cells);

var tables = DocumentApp.openById(docId).getBody().getTables();
var tables_ct = DocumentApp.openById(docId).getBody().getTables().push();

Logger.log(tables);
Logger.log(tables_ct);

//Looking for code to add a blank row to the end of first table.

//Looking for code to delete the second table.

}

THANKS!


Solution

  • To append empty row to table 1. Use this:

    function appendRow() {
      var body = DocumentApp.openById("doc id").getBody();
      var tables = body.getTables();
      var firstTable = tables[0].appendTableRow();
      firstTable.appendTableCell();
      firstTable.appendTableCell();
    }
    

    To delete the 2nd table in the doc. Use this:

    function deleteTable(){
      var body = DocumentApp.openById("doc id").getBody();
      var tables = body.getTables();
      tables[1].removeFromParent();
    }
    

    Note: The sequence of the Table Object in getTables() array are based on the position of the table in your Docs (top to bottom) and 0 is the starting index.

    Example:

    Before:

    enter image description here

    After executing appendRow():

    enter image description here

    After executing deleteTable():

    enter image description here

    References: