获取 sheet 的列表和 google 中最新的 sheet spreadsheet api v4 in Python
Get list of sheets and latest sheet in google spreadsheet api v4 in Python
我正在尝试在 google official documentation 之后的 python 3 中读取和写入不同 sheet 的值。尽管我能够在下面提到的代码块中使用范围 属性 in rangeName = 'Class Data!A2:E'
从某些 sheets 读取值:
discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
'version=v4')
service = discovery.build('sheets', 'v4', http=http,
discoveryServiceUrl=discoveryUrl)
spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
rangeName = 'Class Data!A2:E'
result = service.spreadsheets().values().get(
spreadsheetId=spreadsheetId, range=rangeName).execute()
values = result.get('values', [])
我正在尝试使用 sample code from here:
写入值
requests.append({
'updateCells': {
'start': {'sheetId': 0, 'rowIndex': 0, 'columnIndex': 0},
'rows': [
{
'values': [
{
'userEnteredValue': {'numberValue': 1},
'userEnteredFormat': {'backgroundColor': {'red': 1}}
}, {
'userEnteredValue': {'numberValue': 2},
'userEnteredFormat': {'backgroundColor': {'blue': 1}}
}, {
'userEnteredValue': {'numberValue': 3},
'userEnteredFormat': {'backgroundColor': {'green': 1}}
}
]
}
],
'fields': 'userEnteredValue,userEnteredFormat.backgroundColor'
}
})
batchUpdateRequest = {'requests': requests}
service.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_id,
body=batchUpdateRequest).execute()
我面临的问题是我无法从官方文档中保留最新的 sheet 名称或 ID,并且最新的 api 修订版正在生成随机 gid(我们可能不知道什么会将是 sheet gid)。有什么方法可以使用 google sheet api v4 引用 sheet 列表或传播 sheet 最新修订的 sheet 名称或 ID?
您可以在电子表格上使用 "get" 方法获取工作表列表:
sheet_metadata = service.spreadsheets().get(spreadsheetId=spreadsheet_id).execute()
sheets = sheet_metadata.get('sheets', '')
title = sheets[0].get("properties", {}).get("title", "Sheet1")
sheet_id = sheets[0].get("properties", {}).get("sheetId", 0)
还没有人在 PHP 库的 SO 上问过这个问题,但我只是想在这里添加这个答案,因为这是相关问题的第一个 Google 结果。
<?php
$sheets = array();
// ... load library and set up client ...
$service = new Google_Service_Sheets($client);
$response = $service->spreadsheets->get($spreadsheetId);
foreach($response->getSheets() as $s) {
$sheets[] = $s['properties']['title'];
}
return $sheets;
?>
这是一个C#方法,returns指定sheet号码的sheetid值和Spreadsheetid。
这是使用 Google Sheets API v4.
制作的
private static Int32 GetSheetIdFromSheetNum(string sSpreadsheetId, Int32 iSheetNum, SheetsService gsService, ref string sTitle)
{ //Get the Sheet Id for the specified sheet number and Spreadsheet id.
Int32 iSheetId = -1;
Int32 iLoop = -1;
//Google.Apis.Sheets.v4.Data.Sheet gsSheet;
Google.Apis.Sheets.v4.Data.Spreadsheet gsSpreadsheet;
try
{
sTitle = string.Empty;
gsSpreadsheet = gsService.Spreadsheets.Get(sSpreadsheetId).Execute();
foreach (Sheet gsSheet in gsSpreadsheet.Sheets)
{
iLoop += 1;
if (iLoop != iSheetNum)
{
continue;
}
iSheetId = (gsSheet.Properties.SheetId).GetValueOrDefault(-1);
sTitle = gsSheet.Properties.Title;
break;
}
}
catch (Exception ex)
{
// Do error processing here.
}
return iSheetId;
} //GetSheetIdFromSheetNum
对于python。
service = build('sheets', 'v4', credentials=creds)
sheet_metadata = service.spreadsheets().get(spreadsheetId=SHEET_ID).execute()
properties = sheet_metadata.get('sheets')
for item in properties:
if item.get("properties").get('title') == 'SHEET_TITILE':
sheet_id = (item.get("properties").get('sheetId'))
print (sheet_id)
对于那些正在寻找 nodejs 解决方案的人:
const { google } = require("googleapis")
// Assuming auth has already been generated
const getSheets = async (auth, spreadsheetId) => {
const sheets = google.sheets({version: "v4", auth});
const result = (await sheets.spreadsheets.get({
spreadsheetId
})).data.sheets.map((sheet) => {
return sheet.properties.title
})
return result
}
This 是从 await sheets.spreadsheets.get({ spreadsheetId })
得到 return 的内容
然后,使用 this type,我映射 data.sheets
和 return 所有标题的结果。
看起来 return 标题是按照实际 google sheet.
的顺序排列的
如果您尝试生成授权令牌,则 look here
sheet_metadata = service.spreadsheets().get(spreadsheetId=sheet_id).execute()
sheets = sheet_metadata.get('sheets', '')
for title in sheets:
print('%s' % (title.get("properties", {}).get("title", "Sheet1")))
SAMPLE_RANGE_NAME = title.get("properties", {}).get("title", "Sheet1") ;
result = sheet.values().get(spreadsheetId=sheet_id,
range=SAMPLE_RANGE_NAME).execute();
print(result);
values = result.get('values', []);
if not values:
print('No data found.')
else:
print('Name, Major:')
for row in values:
# Print columns A and E, which correspond to indices 0 and 4.
print('%s, %s' % (row[0], row[1]))
import gspread
from oauth2client.service_account import ServiceAccountCredentials as sac
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
creds = sac.from_json_keyfile_name('client_secrets.json', scope)
client = gspread.authorize(creds)
sheet = client.open_by_url(url)
flag = True
i = 0
while flag:
try:
ith = sheet.get_worksheet(i)
i += 1
print(ith)
except Exception as e:
print(e)
flag = False
print(f'Total worksheet = {i}')
# Output:
# ---------------------------
# <Worksheet 'Form Responses 1' id:30127793>
# <Worksheet 'Sheet2' id:1033101728>
# index 2 not found
# Total worksheet = 2
我正在尝试在 google official documentation 之后的 python 3 中读取和写入不同 sheet 的值。尽管我能够在下面提到的代码块中使用范围 属性 in rangeName = 'Class Data!A2:E'
从某些 sheets 读取值:
discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
'version=v4')
service = discovery.build('sheets', 'v4', http=http,
discoveryServiceUrl=discoveryUrl)
spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
rangeName = 'Class Data!A2:E'
result = service.spreadsheets().values().get(
spreadsheetId=spreadsheetId, range=rangeName).execute()
values = result.get('values', [])
我正在尝试使用 sample code from here:
写入值requests.append({
'updateCells': {
'start': {'sheetId': 0, 'rowIndex': 0, 'columnIndex': 0},
'rows': [
{
'values': [
{
'userEnteredValue': {'numberValue': 1},
'userEnteredFormat': {'backgroundColor': {'red': 1}}
}, {
'userEnteredValue': {'numberValue': 2},
'userEnteredFormat': {'backgroundColor': {'blue': 1}}
}, {
'userEnteredValue': {'numberValue': 3},
'userEnteredFormat': {'backgroundColor': {'green': 1}}
}
]
}
],
'fields': 'userEnteredValue,userEnteredFormat.backgroundColor'
}
})
batchUpdateRequest = {'requests': requests}
service.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_id,
body=batchUpdateRequest).execute()
我面临的问题是我无法从官方文档中保留最新的 sheet 名称或 ID,并且最新的 api 修订版正在生成随机 gid(我们可能不知道什么会将是 sheet gid)。有什么方法可以使用 google sheet api v4 引用 sheet 列表或传播 sheet 最新修订的 sheet 名称或 ID?
您可以在电子表格上使用 "get" 方法获取工作表列表:
sheet_metadata = service.spreadsheets().get(spreadsheetId=spreadsheet_id).execute()
sheets = sheet_metadata.get('sheets', '')
title = sheets[0].get("properties", {}).get("title", "Sheet1")
sheet_id = sheets[0].get("properties", {}).get("sheetId", 0)
还没有人在 PHP 库的 SO 上问过这个问题,但我只是想在这里添加这个答案,因为这是相关问题的第一个 Google 结果。
<?php
$sheets = array();
// ... load library and set up client ...
$service = new Google_Service_Sheets($client);
$response = $service->spreadsheets->get($spreadsheetId);
foreach($response->getSheets() as $s) {
$sheets[] = $s['properties']['title'];
}
return $sheets;
?>
这是一个C#方法,returns指定sheet号码的sheetid值和Spreadsheetid。
这是使用 Google Sheets API v4.
制作的 private static Int32 GetSheetIdFromSheetNum(string sSpreadsheetId, Int32 iSheetNum, SheetsService gsService, ref string sTitle)
{ //Get the Sheet Id for the specified sheet number and Spreadsheet id.
Int32 iSheetId = -1;
Int32 iLoop = -1;
//Google.Apis.Sheets.v4.Data.Sheet gsSheet;
Google.Apis.Sheets.v4.Data.Spreadsheet gsSpreadsheet;
try
{
sTitle = string.Empty;
gsSpreadsheet = gsService.Spreadsheets.Get(sSpreadsheetId).Execute();
foreach (Sheet gsSheet in gsSpreadsheet.Sheets)
{
iLoop += 1;
if (iLoop != iSheetNum)
{
continue;
}
iSheetId = (gsSheet.Properties.SheetId).GetValueOrDefault(-1);
sTitle = gsSheet.Properties.Title;
break;
}
}
catch (Exception ex)
{
// Do error processing here.
}
return iSheetId;
} //GetSheetIdFromSheetNum
对于python。
service = build('sheets', 'v4', credentials=creds)
sheet_metadata = service.spreadsheets().get(spreadsheetId=SHEET_ID).execute()
properties = sheet_metadata.get('sheets')
for item in properties:
if item.get("properties").get('title') == 'SHEET_TITILE':
sheet_id = (item.get("properties").get('sheetId'))
print (sheet_id)
对于那些正在寻找 nodejs 解决方案的人:
const { google } = require("googleapis")
// Assuming auth has already been generated
const getSheets = async (auth, spreadsheetId) => {
const sheets = google.sheets({version: "v4", auth});
const result = (await sheets.spreadsheets.get({
spreadsheetId
})).data.sheets.map((sheet) => {
return sheet.properties.title
})
return result
}
This 是从 await sheets.spreadsheets.get({ spreadsheetId })
然后,使用 this type,我映射 data.sheets
和 return 所有标题的结果。
看起来 return 标题是按照实际 google sheet.
的顺序排列的如果您尝试生成授权令牌,则 look here
sheet_metadata = service.spreadsheets().get(spreadsheetId=sheet_id).execute()
sheets = sheet_metadata.get('sheets', '')
for title in sheets:
print('%s' % (title.get("properties", {}).get("title", "Sheet1")))
SAMPLE_RANGE_NAME = title.get("properties", {}).get("title", "Sheet1") ;
result = sheet.values().get(spreadsheetId=sheet_id,
range=SAMPLE_RANGE_NAME).execute();
print(result);
values = result.get('values', []);
if not values:
print('No data found.')
else:
print('Name, Major:')
for row in values:
# Print columns A and E, which correspond to indices 0 and 4.
print('%s, %s' % (row[0], row[1]))
import gspread
from oauth2client.service_account import ServiceAccountCredentials as sac
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
creds = sac.from_json_keyfile_name('client_secrets.json', scope)
client = gspread.authorize(creds)
sheet = client.open_by_url(url)
flag = True
i = 0
while flag:
try:
ith = sheet.get_worksheet(i)
i += 1
print(ith)
except Exception as e:
print(e)
flag = False
print(f'Total worksheet = {i}')
# Output:
# ---------------------------
# <Worksheet 'Form Responses 1' id:30127793>
# <Worksheet 'Sheet2' id:1033101728>
# index 2 not found
# Total worksheet = 2