【发布时间】:2017-02-19 09:46:01
【问题描述】:
对于 PHP,Google Sheets API v4 documentation 并不清楚如何在现有电子表格中创建新工作表(也称为“选项卡”)。
奇怪的是,我可以通过 API Explorer 使用 batchUpdate 来完成此操作,但他们没有解释如何在 PHP 中执行此操作。
【问题讨论】:
标签: php google-api google-sheets-api
对于 PHP,Google Sheets API v4 documentation 并不清楚如何在现有电子表格中创建新工作表(也称为“选项卡”)。
奇怪的是,我可以通过 API Explorer 使用 batchUpdate 来完成此操作,但他们没有解释如何在 PHP 中执行此操作。
【问题讨论】:
标签: php google-api google-sheets-api
看起来文档说我们必须使用来自$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 对象,然后使用它来获取 Google_Service_Sheets 类的 $service 对象,并且假设您已将 $sSpreadsheetID 分配给您的 ID电子表格,那么上述例程将尝试在您的电子表格中添加一个名为“新工作表”的新标签,而不破坏任何现有的标签,并且如果该标签已存在,则不会显示错误。那时,您可以使用 A1 Notation 来处理该新工作表。
【讨论】:
看看这个
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()
【讨论】:
这是使用 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)
【讨论】: