如何为Google表格命名并归入指定文件夹?参数咨询
Google Sheets API 创建带名称并指定文件夹的表格参数说明
一、为表格命名的参数
要给创建的表格命名,需要在POST请求的**请求体(body)**中添加properties.title字段,同时要把请求头的Content-Type改为application/json(原请求的Accept头可保留,需新增该类型)。
修改后的示例代码:
fetch("https://sheets.googleapis.com/v4/spreadsheets?access_token=" + access_token, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ properties: { title: "我的自定义表格名称" // 替换为你需要的表格名称 } }) }).then(response => response.json()).then(json => { console.log(json); // 返回结果包含表格ID等核心信息 });
二、将表格分配到指定文件夹的方法
Google Sheets API本身不支持创建时直接指定文件夹,需结合Google Drive API完成,以下是两种常用方式:
方式1:先创建表格,再移动到目标文件夹
- 用上面的代码创建带名称的表格,获取返回的表格
id - 调用Drive API的
Files.update接口,将表格添加到目标文件夹(若要从默认根文件夹移除,可添加removeParents参数)
示例代码:
// 假设已获取表格ID:sheetId,目标文件夹ID:folderId fetch(`https://www.googleapis.com/drive/v3/files/${sheetId}?access_token=${access_token}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ addParents: folderId, // 指定要添加的目标文件夹 removeParents: 'root' // 可选:若需从根文件夹移除则保留,否则删除此行 }) }).then(response => response.json()).then(json => { console.log("表格已移动到指定文件夹", json); });
方式2:直接用Drive API创建表格(推荐)
调用Drive API的Files.create接口,一步完成表格创建与文件夹指定:
fetch(`https://www.googleapis.com/drive/v3/files?access_token=${access_token}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: "我的自定义表格名称", // 表格名称 mimeType: "application/vnd.google-apps.spreadsheet", // 指定为Google表格类型 parents: [folderId] // 目标文件夹ID,以数组形式传入 }) }).then(response => response.json()).then(json => { console.log("已创建并指定文件夹的表格", json); });
注意:两种方式都需要确保你的access_token拥有sheets.create和drive.files的权限。
内容的提问来源于stack exchange,提问作者Bret Joseph
相关产品推荐
相关产品推荐

