如何使用 Google Sheets API 在电子表格中创建新工作表

Pau*_*aul 1 python google-sheets google-sheets-api

在此输入图像描述

官方文档显示了如何创建电子表格,但我找不到如何创建工作表。我如何在 Python 中做到这一点?

小智 6

@PCDSandwichMan 的答案使用gspread,这是一个非常有用的第三方库,可以简化 Python 中的 Sheets API。不过,并非所有 Google 的 API 都有这样的库,因此您可能也想以常规方式学习。

作为替代方案,如果您想使用 Google 的 API,您可以查看Google 的 Python API 库的文档。对电子表格属性的大多数直接更改都是通过spreadsheets().batchUpdate(). 以下是基于 Google 的Python 快速入门的示例,其中添加了新工作表。

import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

SCOPES = ['https://www.googleapis.com/auth/spreadsheets']

# The ID of the spreadsheet
YOUR_SPREADSHEET = 'some-id'

def main():
    creds = None
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)

        with open('token.json', 'w') as token:
            token.write(creds.to_json())
    try:
        sheetservice = build('sheets', 'v4', credentials=creds)
        
        body = {
            "requests":{
                "addSheet":{
                    "properties":{
                        "title":"New Sheet"
                    }
                }
            }
        }

        sheetservice.spreadsheets().batchUpdate(spreadsheetId=YOUR_SPREADSHEET, body=body).execute()
        
    except HttpError as err:
        print(err)
Run Code Online (Sandbox Code Playgroud)

大部分是授权。相关部分在try块内。您几乎只需使用batchUpdate()电子表格的 ID 和body包含您想要发出的所有请求的对象来调用该方法即可。

sheetservice = build('sheets', 'v4', credentials=creds)
        
body = {
    "requests":[{
        "addSheet":{
            "properties":{
                "title":"New Sheet"
            }
        }
    }]
}

sheetservice.spreadsheets().batchUpdate(spreadsheetId=YOUR_SPREADSHEET, body=body).execute()
Run Code Online (Sandbox Code Playgroud)

资料来源: