如何在脚本中更改 Google Docs table 单元格内的文本颜色?

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

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

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

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

如何将格式应用到每个单独的单元格和指定的文本范围内?有 this way to set the background of a cell 但设置整个单元格的背景而不是单元格的一部分。

我相信你的目标如下。

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

为此,这个答案怎么样?

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

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

示例脚本:

在此示例脚本中,将包含 2 x 2 个单元格的 table 附加到文档正文。并且修改了单元格"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")

结果:

当上面的示例脚本为运行时,可以得到如下结果

参考文献: