我已经弄清楚了如何从我创建的预算电子表格中读取值,但是我不知道如何使用Sheets API V4创建新的电子表格。到目前为止,我已经为这个问题苦苦挣扎了5个月,之前有人解决过这个问题吗?
这是我的代码:
// READ - WORKING!
router.get("/get", (req, res) => {
var id = '1LoSF_4Z9aoiVvDsjFV9CMOd--vvz3fERfOPajVb2sv8';
var params = 'https://sheets.googleapis.com/v4/spreadsheets/?key='
var url = params + apiKey;
request(`https://sheets.googleapis.com/v4/spreadsheets/${id}?key=${apiKey}`, (error, response, body) => {
console.log("Body", body);
});
})
// Create - NOT WORKING!
router.post('/create', (req,res)=>{
request({
method: 'POST',
uri: `https://sheets.googleapis.com/v4/spreadsheets?fields=properties%2Ftitle&key=${apiKey}`
}, (error, response, body)=>{
console.log(body);
//Logs the body of the newly created spreadsheet
})
})
我使用了Google API Explorer中的指南,您可以在这里找到它:
https://developers.google.com/apis-explorer/#p/sheets/v4/sheets.spreadsheets.create
谢谢!
答案 0 :(得分:0)
此修改如何?
headers
。body
,以提供创建的电子表格的标题。request({
method: 'POST',
uri: 'https://sheets.googleapis.com/v4/spreadsheets?fields=properties%2Ftitle%2CspreadsheetId',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + accessToken,
},
body: JSON.stringify({properties: {title: "sampleTitle"}}),
}, (error, response, body) => {
console.log(body);
});
https://www.googleapis.com/auth/spreadsheets
的访问令牌。此范围用于创建电子表格。答案 1 :(得分:0)
我实际上已经开始工作了!与先前的回复类似(感谢您Tanaike !!)。
request({
method: 'POST',
url: 'https://sheets.googleapis.com/v4/spreadsheets',
headers:{
'Authorization': 'Bearer (access token goes here)'
},
body: JSON.stringify({
properties: {
title: "Spreadsheet Title Goes Here"
}
})}, (error, response, body)=>{
if(!error && response.statusCode == 200){
var info = JSON.parse(body);
console.log(info);
} else {
console.log(error);
}
})