Home‎ > ‎

Create table in Google Document using Apps Script

In this tutorial, I am going to tell you how you can create a Table with data inside a Google Document using Google Apps Script. This is a very simple code which creates a Basic Table in Google Document, applies some row and cell styles in Header row as well as data row.

Let us define some styles first.

This style will be used with table cells in Header row. A dark green background color, bold text with white color.

var headerStyle = {};  
headerStyle[DocumentApp.Attribute.BACKGROUND_COLOR] = '#336600';  
headerStyle[DocumentApp.Attribute.BOLD] = true;  
headerStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#FFFFFF';

This style will be used with table cells in other than header row. This style defines text with normal font-weight and black color

var cellStyle = {};
cellStyle[DocumentApp.Attribute.BOLD] = false;  
cellStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#000000';

Below is some code to define style for a paragraph. This style will be used with the text inside a cell. By default, a paragraph in a Google Document has some space after paragraph, so will reduce that space to zero. Also, we will change the line spacing to 1. 

var paraStyle = {};
paraStyle[DocumentApp.Attribute.SPACING_AFTER] = 0;
paraStyle[DocumentApp.Attribute.LINE_SPACING] = 1;

Now we will access the document to which we are going to append the table. You can access the document in many ways.
If you are creating this Apps Script Project  inside a Google Document container, you can use getActiveDocument() method.

var doc = DocumentApp.getActiveDocument(); 
var doc = DocumentApp.openById('ID_OF_DOCUMENT'); 
var doc = DocumentApp.openByUrl('URL_OF_DOCUMENT');

Now get the body of the document in which we will append the table.

var body = doc.getBody();

Now add a table inside the body. 
var table = body.appendTable();

Above code line will just add a table in the body without any table row or cells so this will not be visible to you in document until you add some rows and cells so let us add some rows and cells inside those rows. 

var tr = table.appendTableRow();
var td = tr.appendTableCell(‘My Text’);

apply the style to cell depending on if it belongs to header row or a data row.


Now, let us add attributes to the paragraph/text inside the cell.

var paraInCell = td.getChild(0).asParagraph();

As we will be adding multiple rows and cells in the table, we will using above code inside a for loop.