Home > other >  Create a non uniform table in Google Docs Apss Script
Create a non uniform table in Google Docs Apss Script

Time:02-19

I am looking at two methods to achieve what I want. Neither have been successful.

What I want: By clicking a menu button I want a table inserted in to the Google Doc I am editing (In MS Word I would just have used a macro). The table is Non uniform but all rows should fill the width of the document.

Method 1: I made the table in another Google Doc and tried to "copy/paste" the content, but I constant end up with an error:

var docToCopyID = '---The Id of the Google Doc with only a table in it---';
var bodyToCopy = DocumentApp.openById(docToCopyID).getBody();
var tableToCopy = bodyToCopy.getTables[0];

var docBody = DocumentApp.getActiveDocument().getBody();

docBody.appendTable(tableToCopy);

The Error I get is (translated from Danish): Exception: Unexpected error, method or propperty appendTable when object DocumentApp.Body should be read.

Method 2: I tried to build the table by code, but the result is that there is a blank line between the cells:

  var docBody = DocumentApp.getActiveDocument().getBody();
  
  var cells1 = [
  ['Beslutning'],
  ['']
  ];
  var cells2 = [
  ['Ansvarlig','','Dato','dd.mm.yyyy']
  ];
  
  docBody.appendTable(cells1);
  docBody.appendTable(cells2);

Whether I end up with clean code or using the copy/paste method is indifferent for me. Thanks in advance!

CodePudding user response:

Probably it's need to correct the two lines in your frist code:

function myFunction() {
  var docToCopyID = '###';
  var bodyToCopy = DocumentApp.openById(docToCopyID).getBody();
  var tableToCopy = bodyToCopy.getTables()[0];  // <--- here  ()

  var docBody = DocumentApp.getActiveDocument().getBody();

  docBody.appendTable(tableToCopy.copy());      // <--- here  .copy()
}

As for the Method 2, it should work in this notation:

function create_table() {
  var docBody = DocumentApp.getActiveDocument().getBody();

  var row1 = ['Beslutning', '', '', ''];
  var row2 = ['Ansvarlig', '', 'Dato', 'dd.mm.yyyy'];

  var table = [row1, row2];

  docBody.appendTable(table);
}

But to be honest I don't understand what do you mean by 'non uniform' table. Could you show how they look like?

  • Related