首页 > 解决方案 > 在 Chrome 扩展中使用 Google API 电子表格 JS 删除值

问题描述

我有向谷歌文档发送请求并添加值的代码。put 请求运行良好,但我想删除我发送的这个值。我怎样才能做到这一点?这是我的代码:background-js:

chrome.identity.getAuthToken({ 'interactive': true }, getToken);
function getToken(token) {
console.log('this is the token: ', token);

 var params = {
    "range":"Sheet1!A1:B1",
    "majorDimension": "ROWS",
      "values": [
      ["Hello","world"]
    ],
  }
  let init = {
    method: 'PUT',
    async: true,
    body: JSON.stringify(params),
    headers: {
      Authorization: 'Bearer ' + token,
      'Content-Type': 'application/json'
    },
    'contentType': 'json',
  };
  fetch(
      "https://sheets.googleapis.com/v4/spreadsheets/1efS6aMlPFqHJJdG8tQw-BNlv9WbA21jQlufsgtMsUmw/values/Sheet1!A1:B1?valueInputOption=USER_ENTERED",
      init)
      .then((response) => console.log(response))

      let request = {
        method: 'GET',
        async: true,
        headers: {
          Authorization: 'Bearer ' + token,
          'Content-Type': 'application/json'
        },
        'contentType': 'json',
      };
      fetch(
          "https://sheets.googleapis.com/v4/spreadsheets/1efS6aMlPFqHJJdG8tQw-BNlv9WbA21jQlufsgtMsUmw/values/Sheet1!A1:B1",
          request)
          .then((response) => response.json())
          .then(function(data) {
            console.log(data)
          });
}

标签: javascriptgoogle-apps-scriptgoogle-chrome-extensionfetchgoogle-sheets-api

解决方案


您可以使用空字符串["",""]而不是 ["Hello","world"] 来清除范围。或者,POST使用Spreadsheets.values.clear

fetch(
      "https://sheets.googleapis.com/v4/spreadsheets/[SPREADSHEET_ID]/values/Sheet1!A1:B1:clear",
       Object.assign({},init,{method:'POST',body:""}))
      .then((response) => console.log(response))

POST如果您想使用updateCellsRequest清除值以及格式、注释等


推荐阅读