如何更改脚本中 Google 文档表格单元格内的文本颜色?

use*_*184 1 javascript google-docs google-apps-script

我正在尝试重现此表,但使用 Google Docs 脚本。

请注意,每个单元格内都有不同的颜色、不同的背景和字体样式。我可以创建一个这样的表:

  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);
Run Code Online (Sandbox Code Playgroud)

如何将格式应用于每个单独的单元格以及指定的文本范围内?有一种方法可以设置单元格的背景,但它设置的是整个单元格的背景而不是单元格的一部分。

Tan*_*ike 5

我相信你的目标如下。

  • 您想要修改表格单元格中文本的文本样式。
  • 您希望使用 Google Apps 脚本来实现此目的。

为此,这个答案怎么样?

在这种情况下,使用以下流程。

  1. 使用 检索每个单元格中的文本对象editAsText()
  2. setBackgroundColor对于检索到的文本对象,使用、setForegroundColorsetBold等修改文本setFontFamily样式。

示例脚本:

在此示例脚本中,一个包含 2 x 2 单元格的表格被附加到文档正文。并且,单元格“A1”和“B2”的文本样式被修改。

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);
}
Run Code Online (Sandbox Code Playgroud)
  • 例如,当您想修改文本的背景颜色时,请使用setBackgroundColor(startOffset, endOffsetInclusive, color)Ref当修改 的文本样式时This is,请使用setBackgroundColor(0, 7, "#FFFF00")

结果:

运行上面的示例脚本,可以获得以下结果。

在此输入图像描述

参考: