5
votes

I creating a google doc by script and want to insert table to it by this code:

  var row1 = "some city"
  var row2 = "some text"
  var rowsData = [[row1, row2]];
  var table = body.appendTable(rowsData);
  table.setBorderWidth(0);
  style[DocumentApp.Attribute.BOLD] = true;
  style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;
  table.setAttributes(style);

I'm expecting that all text in cells will be bold and centered. But I see that only bold attribute applied. I've tried to add some script

 var cell1 = table.getCell(0, 0);
  var cell2 = table.getCell(0, 1);
  cell1.setAttributes(style);
  cell1.editAsText().setAttributes(style);

but no effect.

Please say me how to center text in cell properly!

3

3 Answers

13
votes

Text alignment can`t be applied on "table-cell" item, it can be allplied only on "paragraph" item. To get "paragraph" from "table-cell", you need to do the following:

var cellStyle = {};
cellStyle[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;
tabel.getRow(0).getCell(1).getChild(0).asParagraph().setAttributes(cellStyle)

(thanks to Stefan van Aalst for his answer )

2
votes

Perhaps not doable 5 years ago, when the question was asked. Today, you can use GUI. Select the table (or cells in question), right click on your selection and pick "Table Properties". The pop-up window should look a bit like this:

Docs > Table Properties

You'll find both vertical and horizontal alignment options there.

0
votes

I believe you want to use .setAlignment instead of .setAttribute or style[].

cell1.setAlignment(DocumentApp.HorizontalAlignment.CENTER);