如果您想更改 Google 表格中单元格的颜色,可以使用以下两个选项之一:
1。使用表格 API
要更新文本的颜色,您必须使用spreadsheets.batchUpdate 方法。
请求
POST https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}:batchUpdate
身体
{
"requests": [{
"repeatCell": {
"cell": {
"userEnteredFormat": {
"textFormat": {
"bold": true,
"italic": true,
"foregroundColor": {
"blue": 1.0,
"green": 0.0,
"red": 0.0
}
}
}
},
"range": {
"sheetId": 0,
"startRowIndex": 0,
"endRowIndex": 1
},
"fields": "userEnteredFormat(textFormat)"
}
}]
}
如果您想使用 Java,您可能会受益于查看来自 here 的这个 sn-p 并根据您的任务对其进行调整。
但是,此选项不让您可以仅更改单元格中的部分文本。为此,您应该尝试使用 Apps 脚本。
2。使用 Apps 脚本
由于您想从单元格中更改特定数量的字符,您可以使用以下脚本
function changeColor() {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("A1:A2");
var redColor = SpreadsheetApp.newTextStyle()
.setForegroundColor("#ff0000")
.build();
var purpleColor = SpreadsheetApp.newTextStyle()
.setForegroundColor("#871f78")
.build();
var richTextA1 = SpreadsheetApp.newRichTextValue()
.setText("▶Mike: Hey, How is going on?")
.setTextStyle(0, 6, redColor)
.setTextStyle(7, 28, purpleColor)
.build();
var richTextA2 = SpreadsheetApp.newRichTextValue()
.setText("red words, purple words")
.setTextStyle(0, 10, redColor)
.setTextStyle(11, 23, purpleColor)
.build();
range.setRichTextValues([
[richTextA1],
[richTextA2]
]);
}
上述脚本创建了两种文本样式,然后根据startOffset 和endOffset 参数应用它们,这两个参数实质上表示哪些字符将具有两种文本样式中的一种。
执行上述脚本后,单元格将如下所示:
参考