javascript - 如何在脚本中更改 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);
如何将格式应用于每个单独的单元格并在指定的文本范围内?有一种方法可以设置单元格的背景,但它设置了整个单元格的背景,而不是单元格的一部分。
解决方案
我相信你的目标如下。
- 您想修改表格单元格中的文本中的文本样式。
- 您想使用 Google Apps 脚本实现此目的。
为此,这个答案怎么样?
在这种情况下,使用以下流程。
- 使用 检索每个单元格中的文本对象
editAsText()
。 - 对于检索到的文本对象,使用
setBackgroundColor
、setForegroundColor
、setBold
等修改文本样式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")
.
结果:
运行上述示例脚本时,可以获得以下结果。
参考:
推荐阅读
- java - PreBuiltTransportClient 写入消息:错误 StatusLogger 找不到 log4j2 配置文件
- ios - 一次从所有集合视图单元格内的文本视图中获取文本
- c++ - time_t 的时钟周期和获取时间问题
- python-3.7 - 记录错误:TypeError:需要一个类似字节的对象,而不是“str”
- php - 如何在WordPress中查询所有自定义帖子类型+帖子和页面
- jenkins - 如何通过 jenkinsfile 配置 Checkmarx
- react-native - 在 React Native 中使用 WebView 的正确方法是什么
- tomcat - 如何摆脱无法为 Web 模块创建注释扫描器:在 Tomee 上部署战争文件时出现空错误?
- excel - 当单元格包含特定文本时不要复制(忽略)
- html - 即使最后一个有可用空间,如何在响应式块项目中制作相同的宽度