简体   繁体   English

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

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

With PHP, it is unclear from the Google Sheets API v4 documentation on how to create a new sheet (aka "tab") in an existing spreadsheet.对于 PHP, Google Sheets API v4 文档中不清楚如何在现有电子表格中创建新工作表(又名“标签”)。

I can do it with batchUpdate, oddly, via the API Explorer , but they don't explain from that how to do this in PHP.奇怪的是,我可以通过API Explorer使用 batchUpdate 来完成,但他们没有从中解释如何在 PHP 中执行此操作。

It looks like the documentation is saying that we must use batchUpdate from $service->spreadsheets_values collection.看起来文档说我们必须使用$service->spreadsheets_values集合中的 batchUpdate。 But that's incorrect.但这是不正确的。 It should be the $service->spreadsheets collection.它应该是$service->spreadsheets集合。 The proper answer after a lot of trial and error is:经过大量试验和错误后的正确答案是:

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) {}

Given that you have already authenticated your API to get a $client object, and then used that to get a $service object of class Google_Service_Sheets , and given that you have assigned $sSpreadsheetID to the ID of your spreadsheet, then the above routine will attempt to add a new tab to your spreadsheet named 'New Sheet' without destroying any existing one, and will not show errors if this tab already exists.鉴于您已经验证了您的 API 以获取$client对象,然后使用它来获取类Google_Service_Sheets$service对象,并且您已将$sSpreadsheetID分配给电子表格的 ID,那么上述例程将尝试在不破坏任何现有标签的情况下向您的电子表格添加一个名为“新工作表”的新标签,如果此标签已存在,则不会显示错误。 At that point, you can do something new with that new sheet by addressing it with the A1 Notation .那时,您可以通过使用A1 Notation对新工作表进行处理来做一些新的事情。

Take a look this看看这个

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()

This is how to do it with Node.js client:这是使用 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM