无法使用v4 .net客户端库访问谷歌工作表,特别是使用update和append方法。
get方法运行得很好,我可以从工作表中读取值。但是,当我尝试更新或附加时,我得到的结果是
Google.GoogleApiException: 'Google.Apis.Requests.RequestError Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project. [401] Errors [ Message[Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.] Location[ - ] Reason[unauthorized] Domain[global] ] '
我使用相同的服务初始化来运行这两个代码,但是我得到了错误。
以下是代码
using Google.Apis.Auth.OAuth2;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SheetsQuickstart
{
class Program
{
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-dotnet-quickstart.json
static string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };
static string ApplicationName = "Google Sheets API .NET Quickstart";
static String spreadsheetId = "{{SpreadSheet_ID}}";
static void Main(string[] args)
{
/*
UserCredential credential;
using (var stream =
new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.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,
ApiKey = "{{API_KEY}}",
}
);
// Define request parameters.
String range = "A2:E";
//get request / for reading
SpreadsheetsResource.ValuesResource.GetRequest request = service.Spreadsheets.Values.Get(spreadsheetId, range);
IList<IList<Object>> val = GenerateData();
string newRange = GetRange(service);
//append request
SpreadsheetsResource.ValuesResource.AppendRequest arequest = service.Spreadsheets.Values.Append(new ValueRange() { Values = val }, spreadsheetId, newRange);
ValueRange response = request.Execute();
IList<IList<Object>> values = response.Values;
if (values != null && values.Count > 0)
{
foreach (var row in values)
{
// Print columns A to E, which correspond to indices 0 to 4.
Console.WriteLine("{0}, {1}, {2}, {3}, {4}", row[0], row[1], row[2], row[3], row[4]);
}
}
else
{
Console.WriteLine("No data found.");
}
Console.Read();
arequest.InsertDataOption = SpreadsheetsResource.ValuesResource.AppendRequest.InsertDataOptionEnum.INSERTROWS;
arequest.ValueInputOption = SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum.USERENTERED;
/*
*
* Works till here
*
*/
var aresponse = arequest.Execute();
Console.WriteLine("Inserted");
Console.Read();
}
private static IList<IList<Object>> GenerateData()
{
List<IList<Object>> objNewRecords = new List<IList<Object>>();
IList<Object> obj = new List<Object>();
obj.Add("Column - 1");
obj.Add("Column - 2");
obj.Add("Column - 3");
obj.Add("Column - 4");
obj.Add("Column - 5");
objNewRecords.Add(obj);
return objNewRecords;
}
protected static string GetRange(SheetsService service)
{
// Define request parameters.
// String spreadsheetId = ;
String range = "A:E";
SpreadsheetsResource.ValuesResource.GetRequest getRequest =
service.Spreadsheets.Values.Get(spreadsheetId, range);
ValueRange getResponse = getRequest.Execute();
IList<IList<Object>> getValues = getResponse.Values;
int currentCount = getValues.Count() + 2;
String newRange = "A" + currentCount + ":A";
return newRange;
}
}
}
发布于 2018-01-23 03:25:59
我不确定您是否可以使用API密钥写入Google工作表,但请检查您是否已将其设置为完全公共访问权限,而不仅仅是读取公共访问权限。如果这不起作用,请继续阅读。
API密钥用于访问公共数据。虽然您可以使用它从公共Google工作表中读取数据,但您不能对其进行写入。这可能是由于api密钥的授权范围不足所致。
您需要使用具有适当写入范围的oauth2或服务帐户。
https://stackoverflow.com/questions/48388789
复制相似问题