How to Set Horizontal Alignment On A Table In Apps

2019-07-13 01:48发布

I am not able to find a way to horizontally align a table in a Google Doc using Google Apps Script. I have thoroughly checked all of the documentation, and also blindly tried several approaches.

Attempt One:

var cells = [
  ['Company', rowData[3]],
  ['Title', rowData[4]],
];

var tableStyle = {};
tableStyle[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.RIGHT;

var mentorTable = body.appendTable(cells);

var myTable = body.appendTable(cells);
myTable.setAttributes(tableStyle);

Attempt Two:

var cells = [
  ['Company', rowData[3]],
  ['Title', rowData[4]],
];

var mentorTable = body.appendTable(cells);
myTable.setAlignment(DocumentApp.HorizontalAlignment.RIGHT);

The Google Docs UI supports changing this attribute from the "Table Properties" menu option.

Any thoughts on how to align a table using Google Apps Script?

1条回答
不美不萌又怎样
2楼-- · 2019-07-13 02:06

I also though you could do it setting the attributes to the complete table, but i could only do it getting the content of each cell and then add the attribute.

In the following code I look for the tables in the document, go to each cell and then apply the formatting. I know this shouldn't be like that but couldn't find a easier way to do it.

Hope it helps.

function myFunction() {
  var doc = DocumentApp.getActiveDocument();

   var style = {};
   style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.RIGHT;

  var body  = doc.getBody();

  for(var i = 0 ; i < body.getNumChildren(); i++)
  {
    if(body.getChild(i).getType() ==  'TABLE')
    {
      var table = body.getChild(i).asTable();
      var rows = table.getNumRows();
      var cols = table.getChild(0).asTableRow().getNumChildren();

      for(var j =0 ; j< rows; j++)
      {
        for(var k =0; k<cols; k++)
        {
          body.getChild(i).asTable().getCell(j,k).getChild(0).setAttributes(style);
        }      
      }
    }
  }  
}
查看更多
登录 后发表回答