我相信你的目标如下。
- 您想使用 Sheets API 从电子表格中检索富文本数据。
在这种情况下,我认为使用“spreadsheets.get”的方法可以实现您的目标。但是当你使用它时,请设置字段。这样就可以检索富文本数据了。
端点:
https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}?ranges=Sheet1!A1&fields=sheets
- 此端点使用
sheets 作为fields。此外,可以使用sheets(data(rowData(values(textFormatRuns))))。并且该值是从“Sheet1”中的“A1”单元格中检索的。
- 在这种情况下,没有进行 URL 编码。所以当你使用这个时,请对查询参数进行 URL 编码。
curl 命令示例:
curl \
'https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}?ranges=Sheet1!A1&fields=sheets' \
--header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
--header 'Accept: application/json' \
--compressed
样本值:
当从上面带有sheets(data(rowData(values(textFormatRuns))))字段的单元格中检索富文本的数据时,得到如下值。
{
"sheets": [
{
"data": [
{
"rowData": [
{
"values": [
{
"textFormatRuns": [
{
"format": {
"foregroundColor": {
"red": 1
},
"bold": true,
"foregroundColorStyle": {
"rgbColor": {
"red": 1
}
}
}
},
{
"startIndex": 1,
"format": {
"fontSize": 18
}
},
{
"startIndex": 5,
"format": {
"foregroundColor": {
"red": 1
},
"italic": true,
"foregroundColorStyle": {
"rgbColor": {
"red": 1
}
}
}
},
{
"startIndex": 6,
"format": {}
},
{
"startIndex": 7,
"format": {
"foregroundColor": {
"blue": 1
},
"bold": true,
"italic": true,
"foregroundColorStyle": {
"rgbColor": {
"blue": 1
}
}
}
}
]
}
]
}
]
}
]
}
]
}
Google Apps 脚本:
当使用 Google Apps Script 时,示例脚本如下。
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
const richTextValue = sheet.getRange("A1").getRichTextValue();
const res = richTextValue.getRuns().map(r => ({
text: r.getText(),
foregroundColor: r.getTextStyle().getForegroundColor(),
fontSize: r.getTextStyle().getFontSize(),
bold: r.getTextStyle().isBold(),
italic: r.getTextStyle().isItalic()
}));
console.log(res)
-
使用
getRichTextValue()。当您想从多个单元格中检索富文本的数据时,您也可以使用getRichTextValues()。
结果:
使用上述单元格时,返回以下值。
[
{
"text": "s",
"foregroundColor": "#ff0000",
"fontSize": 36,
"bold": true,
"italic": false
},
{
"text": "ampl",
"foregroundColor": "#000000",
"fontSize": 18,
"bold": false,
"italic": false
},
{
"text": "e",
"foregroundColor": "#ff0000",
"fontSize": 36,
"bold": false,
"italic": true
},
{
"text": " ",
"foregroundColor": "#000000",
"fontSize": 36,
"bold": false,
"italic": false
},
{
"text": "text",
"foregroundColor": "#0000ff",
"fontSize": 36,
"bold": true,
"italic": true
}
]
Python:
使用python脚本时,变成如下。响应值与 curl 命令相同。在这种情况下,您也可以在官方文档中看到示例脚本。 Ref
spreadsheet_id = '###' # Please set Spreadsheeet ID.
ranges = 'Sheet1!A1' # Please set range as a1Notation.
service = build('sheets', 'v4', credentials=creds)
fields = 'sheets(data(rowData(values(textFormatRuns))))'
res = service.spreadsheets().get(spreadsheetId=spreadsheet_id, ranges=ranges, fields=fields).execute()
print(res)
注意:
- 当您想使用Sheets API确认单元格中的文本数据时,例如可以使用
userEnteredValue和formattedValue。
参考资料: