c# - 从 .NET 和 Python 连接 o google 电子表格
问题描述
尝试使用 C# 客户端和 Python 获取 Google 电子表格表格内容。
当 python 返回错误时,C# 客户端工作正常:
googleapiclient.errors.HttpError: <HttpError 404 when requesting https://sheets.googleapis.com/v4/spreadsheets/IAD2okAWZD7anbt5L4ybgD2dxHBGmsY6IkNIWHBQkBM/values/new%20first%20sheet%21A1?alt=json returned "Requested entity was not found.">
如果我在浏览器中打开错误链接,我会看到错误:
{
"error": {
"code": 403,
"message": "The request is missing a valid API key.",
"status": "PERMISSION_DENIED"
}
}
Python客户端可能有什么问题?
C#客户端:
private void button1_Click(object sender, EventArgs e)
{
string ApplicationName = "aaa";
UserCredential credential;
using (var stream =new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Google Sheets API service.
var service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
String range = "new first sheet!A2:E";//mano
SpreadsheetsResource.ValuesResource.GetRequest request =service.Spreadsheets.Values.Get(spreadsheetId, range);
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
ValueRange response = request.Execute();
IList<IList<Object>> values = response.Values;
if (values != null && values.Count > 0)
{
Console.WriteLine("Name, Major");
foreach (var row in values)
{
// Print columns A and E, which correspond to indices 0 and 4.
if (row.Count==1 ) Console.WriteLine("{0}", row[0]);
else
Console.WriteLine("{0}, {1}", row[0], row[1]);
}
}
else
{
Console.WriteLine("No data found.");
}
Console.Read();
}
Python客户端:
class SS:
store = file.Storage('token.json')
try:
creds = store.get()
except Exception as e:
print(traceback.format_exc())
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('sheets', 'v4', http=creds.authorize(Http()))
# Call the Sheets API
SPREADSHEET_ID = 'IAD2okAWZD7anbt5L4ybgD2dxHBGmsY6IkNIWHBQkBM' #my
RANGE_NAME = 'new first sheet!A1' #my
def __init__(self):
print("Constructing")
def get(self):
print("starting get")
result = self.service.spreadsheets().values().get( spreadsheetId=self.SPREADSHEET_ID, range=self.RANGE_NAME).execute()
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[4]))
解决方案
推荐阅读
- php - 尝试在安装 voyager 后运行 php artisan migrate:fresh 它给了我这个错误
- ruby-on-rails - Rails ActiveRecord::PendingMigrationError 上的迁移错误 ruby
- r - 创建直方图矩阵:无 id 变量;使用所有作为测量变量
- vba - 对包含双引号的记录使用 FindRecord
- python - 如何调整我的刮板在 .csv 上的显示方式?
- c++ - 从给定的字符串返回特定子字符串的模式?
- python - 如果重新实例化,则在 python 中处理类删除
- python - 如何让 selenium 尝试 2 xpath 并获得正确的
- r - 改变具有 3 个组的列 - dplyr
- c++ - 无法初始化 m_days[month][day]= 一个对象