如何使用 googleapis 格式化 Google 表格单元格值的一部分?

问题描述 投票:0回答:1

我正在使用 https://www.npmjs.com/package/googleapis 插入数据。我的一个单元格应该包含多个链接,比方说

https://foo
https://bar

这很容易手动完成,我可以查询手动输入的数据并查看格式。有了这个:

const res = await sheets.spreadsheets.get({
    spreadsheetId,
    ranges: ['Intro!A1'],
    includeGridData: true
})

我可以在

res
中看到数据格式;下面是调试数据的屏幕截图。红色圆圈内是单元格的值,蓝色下划线是
textFormatRuns
中定义的第一个链接。

这是我尝试测试格式的方法。这成功地写入了

stringValue
,但是
textFormatRuns
什么也没做

{
  userEnteredValue: {
    stringValue: "ABCDEFGHIJKLMNOP\nabcdefghijklmnop"
  },
  textFormatRuns: [
    {
      format: { bold: true, underline: true, link: { uri: "https://ddg.gg" } }
    },
    {
      format:{}, startIndex: 9,
    }
  ]
}
google-sheets google-api google-sheets-api google-api-nodejs-client
1个回答
0
投票

最终的解决方案是我的

UpdateCellsRequest
包含这部分:`fields:'userEnteredValue',这在某种程度上阻止了格式更新。这对我来说很奇怪。

这是最终的概念证明请求,实际上可以将文本插入单元格并格式化单元格的某些部分(打字稿):

async function writeTest(auth) {
  const sheets = google.sheets({ version: 'v4', auth })
  const spreadsheetId = 'xxxx' // SPREADSHEET ID
  const sheetId = 111111111111 // WORKSHEET ID

  const requests: any = [
    {
      updateCells: {
        start: { sheetId, rowIndex: 0, columnIndex: 0 },
        rows: [
          {
            values: [
              {
                userEnteredValue: {
                  stringValue: "the quick brown fox\nlorem ipsum dolor"
                },
                textFormatRuns: [
                  { startIndex: 3, format: { bold: true } },
                  { startIndex: 6, format: {} },
                  { startIndex: 9, format: { bold: true, link: { uri: "https://ddg.gg" } } },
                  { startIndex: 12, format: {} }
                ]
              }
            ],
          },
        ],
        fields: '*' // This was the critical thing that was wrong!
      },
    }
  ]

  // Variable just helps when debugging
  await sheets.spreadsheets.batchUpdate({
    spreadsheetId: spreadsheetId,
    requestBody: { requests }
  }, {})
}

authorize() // This provides authentication/authorization
  .then(writeTest)

这是结果;请注意粗体格式和可点击的链接

© www.soinside.com 2019 - 2024. All rights reserved.