首页 > 解决方案 > 如何在脚本中更改 Google Docs 表格单元格中的文本颜色?

问题描述

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

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

  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);

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

标签: javascriptgoogle-apps-scriptgoogle-docs

解决方案


我相信你的目标如下。

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

为此,这个答案怎么样?

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

  1. 使用 检索每个单元格中的文本对象editAsText()
  2. 对于检索到的文本对象,使用setBackgroundColorsetForegroundColorsetBold等修改文本样式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);
}
  • 例如,当您要修改文本的背景颜色时,请使用setBackgroundColor(startOffset, endOffsetInclusive, color). Ref修改文字样式时This is,请使用setBackgroundColor(0, 7, "#FFFF00").

结果:

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

在此处输入图像描述

参考:


推荐阅读