You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Google API创建电子表格时如何设置指定邮箱的访问权限

解决方案

谷歌表格的文件权限管理属于Google Drive API的能力范畴,你需要额外调用Drive API完成权限授予,具体操作步骤如下:

1. 调整授权作用域

首先修改你初始化GoogleAuth时的scopes配置,新增Drive权限:

const auth = new GoogleAuth({
    keyFile: 'src/credentials.json',
    scopes: [
        "https://www.googleapis.com/auth/spreadsheets",
        "https://www.googleapis.com/auth/drive"
    ]
})

注意:修改scope后需要确认你的Google Cloud项目已启用Google Drive API,否则调用时会报权限错误。

2. 新增授权逻辑

在表格创建成功、拿到spreadsheetId后,调用Drive API的权限创建接口为指定邮箱授权,完整代码示例如下:

const {google} = require('googleapis');

// 初始化授权同上文调整后的配置
const auth = new GoogleAuth({
    keyFile: 'src/credentials.json',
    scopes: [
        "https://www.googleapis.com/auth/spreadsheets",
        "https://www.googleapis.com/auth/drive"
    ]
})

const client = await auth.getClient()
const googleSheets = google.sheets({version:"v4", auth: client})
// 初始化Drive客户端
const googleDrive = google.drive({version: "v3", auth: client})

let resource = {
    properties: {
        title: 'Test'
    },
}

googleSheets.spreadsheets.create(
    {
        resource,
        fields: 'spreadsheetId'
    }, 
    async (err, spreadsheet) =>{
        if (err) {
          console.log(err);
          return;
        }
        const sheetId = spreadsheet.data.spreadsheetId;
        console.log(`表格创建成功,ID:${sheetId}`);

        // 授予指定邮箱权限的逻辑
        try {
            await googleDrive.permissions.create({
                fileId: sheetId, // 刚创建的表格ID,谷歌表格ID和Drive文件ID通用
                requestBody: {
                    role: 'writer', // 权限角色可选值:owner/reader/writer/commenter
                    type: 'user',
                    emailAddress: '你要授权的邮箱地址@xxx.com'
                },
                // 如果要授予所有者权限,需要加下面两个参数
                // sendNotificationEmail: true,
                // transferOwnership: true
            })
            console.log('权限授予成功')
        } catch (permErr) {
            console.log('权限授予失败:', permErr)
        }
    }
)

参数说明

  • role:权限角色,常用值如下:
    • reader:只读权限
    • commenter:可评论权限
    • writer:可编辑权限
    • owner:所有者权限,授予时需要额外开启transferOwnership参数,且会给目标邮箱发送通知邮件
  • sendNotificationEmail:是否给被授权人发送通知邮件,默认开启

内容的提问来源于stack exchange,提问作者Alvaro203204

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 12:54:09