如何使用 Google Sheets API v4 在带有 PHP 的电子表格中创建新的 Sheet 或标签

How To Use Google Sheets API v4 To Create New Sheet or Tab in Spreadsheet with PHP

对于 PHP,Google Sheets API v4 documentation 不清楚如何在现有的传播sheet 中创建新的 sheet(也称为 "tab") .

奇怪的是,我可以通过 API Explorer 使用 batchUpdate 来做到这一点,但他们并没有从中解释如何在 PHP 中做到这一点。

文档好像说我们必须使用 $service->spreadsheets_values 集合中的 batchUpdate。但这是不正确的。它应该是 $service->spreadsheets 集合。经过大量试验和错误后的正确答案是:

try {
    $body = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(array(
        'requests' => array(
            'addSheet' => array(
                'properties' => array(
                    'title' => 'New Sheet'
                )
            )
        )
    ));
    $result1 = $service->spreadsheets->batchUpdate($sSpreadsheetID,$body);
} catch(Exception $ignore) {}

鉴于您已经验证了您的 API 以获取 $client 对象,然后使用它来获取 class [=15= 的 $service 对象],并且假定您已将 $sSpreadsheetID 分配给您的传播 sheet 的 ID,那么上述例程将尝试向您的传播 sheet 添加一个名为 'New Sheet' 的新标签不会破坏任何现有的,如果此选项卡已经存在,也不会显示错误。到那时,您可以通过使用 A1 Notation.

对新的 sheet 进行处理来做一些新的事情

这是使用 Node.js 客户端的方法:

    const gsapi = google.sheets({version: 'v4', auth: client})
    const options = {
      spreadsheetId: 'YOUR ID IS EVERYTHING BETWEEN /d/ and /edit on your spreadsheets URL'
    }

    const res = await gsapi.spreadsheets.batchUpdate({
      spreadsheetId: options.spreadsheetId,
      requestBody: {
        requests: [{
          addSheet: {
            properties: {
              title: table,
            }
          }
        }]
      }
    })

    console.log(res)

看看这个

SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
SERVICE_ACCOUNT_FILE = 'credentials.json'
SPREADSHEET_ID = spreadsheetId

creds = None
creds = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

service = discovery.build(
    'sheets', 'v4', credentials=creds, cache_discovery=False)

batch_update_values_request_body = {
        'requests': [
            {
                'addSheet': {
                    'properties': {
                        'title': worksheetName
                    }
                }
            }
        ]
    }
    request = service.spreadsheets().batchUpdate(
        spreadsheetId=SPREADSHEET_ID, body=batch_update_values_request_body)
    response = request.execute()