Search code examples
linecellspacingdoc

Change line spacing in a cell in a Google Doc using Google App Script


I have a Google Doc which has a table that needs updating weekly and content to be inserted from a spreadsheet. I successfully paste in the correct data into each cell but the lines are spaced at 1.15 not single spaced.

Any ideas on how to accomplish this?

Here is the code I have tried:


  const doc = DocumentApp.getActiveDocument();

  var paddingTop = 1.5; // You can adjust the height by modifying this.
  var paddingBottom = 1.5; // You can adjust the height by modifying this.

  var tables = doc.getBody().getTables();
  tables.forEach(table => {
    for (var r = 0; r < table.getNumRows(); r++) {
      var row = table.getRow(r);
      for (var c = 0; c < row.getNumCells(); c++) {
        row.getCell(c).setPaddingTop(paddingTop).setPaddingBottom(paddingBottom);
        var p=row.getCell(c);
        Logger.log(c)
        for(i=0;i<p.length; i++){
          p[i].setLineSpacing(100);
        }
      }
    }
  });

This does not change the line spacing inside the cells at all.


Solution

  • This is what worked for me:

     var paddingTop = 1.5; // You can adjust the height by modifying this.
     var paddingBottom = 1.5; // You can adjust the height by modifying this.
      
      var paraStyle = {};
        paraStyle[DocumentApp.Attribute.LINE_SPACING] = 1;
    
      var tables = doc.getBody().getTables();
      tables.forEach(table => {
        for (var r = 0; r < table.getNumRows(); r++) {
          var row = table.getRow(r);
          for (var c = 0; c < row.getNumCells(); c++) {
            var cell=row.getCell(c);
            cell.setPaddingTop(paddingTop)
            cell.setPaddingBottom(paddingBottom);
            var items = cell.getNumChildren();
            for (var i = 0; i < items; i++){
              var paraInCell = cell.getChild(i).asParagraph();
              paraInCell.setAttributes(paraStyle);
            }
          }
        }
      });