Search code examples
javascriptgoogle-apps-scriptgoogle-docs

How do I change the text color within a cell of a Google Docs table in a script?


I am trying to reproduce this table, but with a Google Docs Script.

Notice that within each cell there are different colors and different background and font styles. I can create a table like this:

  var cells = [
    ['Row 1, Cell 1', 'Row 1, Cell 2'],
    ['Row 2, Cell 1', 'Row 2, Cell 2']
  ];

  // Build a table from the array.
  body.appendTable(cells);

How do I apply the formatting to each individual cell and within a specified range of text? There is this way to set the background of a cell but that sets the background of the entire cell rather than a portion of the cell.


Solution

  • I believe your goal as follows.

    • You want to modify the text style in the texts in the cells of the table.
    • You want to achieve this using Google Apps Script.

    For this, how about this answer?

    In this case, the following flow is used.

    1. Retrieve the text object from each cell using editAsText().
    2. For the retrieved text object, modify the text style using setBackgroundColor, setForegroundColor, setBold, setFontFamily and so on.

    Sample script:

    In this sample script, a table with 2 x 2 cells is appended to the document body. And, the text styles of cells "A1" and "B2" are modified.

    function myFunction() {
      var body = DocumentApp.getActiveDocument().getBody();
    
      var cells = [
        ['This is my text', 'Row 1, Cell 2'],
        ['Row 2, Cell 1', 'Some more text']
      ];
      var table = body.appendTable(cells);
    
      // Modify the text style of the cell "A1".
      table.getCell(0, 0).editAsText()
        .setBackgroundColor(0, 7, "#FFFF00")
        .setForegroundColor(5, 9, "#FF0000")
        .setBackgroundColor(8, 14, "#00BFFF")
        .setBold(8, 14, true);
    
      // Modify the text style of the cell "B2".
      table.getCell(1, 1).editAsText()
        .setFontFamily(5, 13, "IMPACT")
        .setBackgroundColor(5, 13, "#00BFFF")
        .setBold(5, 13, true);
    }
    
    • For example, when you want to modify the background color of text, please use setBackgroundColor(startOffset, endOffsetInclusive, color). Ref When the text style of This is is modified, please use setBackgroundColor(0, 7, "#FFFF00").

    Result:

    When above sample script is run, the following result can be obtained.

    enter image description here

    References: