如何在Chrome扩展中通过Google Sheets API删除已写入的值?
如何删除Google Sheets中已写入的值
嘿,你已经搞定了PUT请求写入内容的逻辑,现在要删除单元格里的已有内容,有两种简单直接的方法可以实现,我结合你的现有代码给你演示:
方法1:用PUT请求覆盖为空值
这种方法和你现有的写入逻辑最贴近,只需要把要写入的values改成对应范围的空值,就能直接覆盖掉原有内容:
chrome.identity.getAuthToken({ 'interactive': true }, getToken); function getToken(token) { console.log('this is the token: ', token); // 构造清空A1:B1的参数:传入对应数量的空字符串 var params = { "range":"Sheet1!A1:B1", "majorDimension": "ROWS", "values": [ ["", ""] ], // 每个位置传空字符串,对应单元格清空 } 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)) // 可选:发送GET请求验证是否清空成功 .then(() => { let request = { method: 'GET', async: true, headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' }, 'contentType': 'json', }; return fetch( "https://sheets.googleapis.com/v4/spreadsheets/1efS6aMlPFqHJJdG8tQw-BNlv9WbA21jQlufsgtMsUmw/values/Sheet1!A1:B1", request ) }) .then((response) => response.json()) .then(function(data) { console.log("清空后的数据:", data) }); }
方法2:使用官方的Clear Values API
Google Sheets API提供了专门的清空接口,这种方法更“标准”,不需要构造空值数组,直接发送请求即可:
chrome.identity.getAuthToken({ 'interactive': true }, getToken); function getToken(token) { console.log('this is the token: ', token); let init = { method: 'POST', // 注意这里用POST请求 async: true, headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' }, 'contentType': 'json', }; // 清空接口的URL格式是:spreadsheets/{表格ID}/values/{范围}:clear fetch( "https://sheets.googleapis.com/v4/spreadsheets/1efS6aMlPFqHJJdG8tQw-BNlv9WbA21jQlufsgtMsUmw/values/Sheet1!A1:B1:clear", init ) .then((response) => console.log(response)) // 可选:验证清空结果 .then(() => { let request = { method: 'GET', async: true, headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' }, 'contentType': 'json', }; return fetch( "https://sheets.googleapis.com/v4/spreadsheets/1efS6aMlPFqHJJdG8tQw-BNlv9WbA21jQlufsgtMsUmw/values/Sheet1!A1:B1", request ) }) .then((response) => response.json()) .then(function(data) { console.log("清空后的数据:", data) }); }
小提示
- 如果要清空更大范围(比如整行、整列),只需要修改URL和参数里的
range即可,比如Sheet1!A:B表示清空A到B列的所有内容。 - 确保你的Google Cloud项目已经启用了Google Sheets API,且授权账号拥有该表格的编辑权限哦。
内容的提问来源于stack exchange,提问作者ONLY GAMES
相关产品推荐
相关产品推荐

