无法使用api密钥访问Google工作表

时间:2018-01-22 19:19:22

标签: c# google-api google-sheets-api google-api-dotnet-client api-key

无法使用v4 .net客户端库专门使用更新和追加方法访问Google工作表。

获取方法工作正常,我能够从工作表中读取值。 但当我尝试更新或追加我正在

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;
    }
}
}

2 个答案:

答案 0 :(得分:2)

我不确定您是否可以使用API​​密钥写入Google表格,但检查您是否已将其设置为完全公开访问权限,而不仅仅是阅读公共访问权限。如果这不起作用继续阅读。

API密钥用于访问公共数据。虽然您可以使用它来阅读公开的Google表格,但您无法写入。这可能是由于api密钥授权范围不足。

您需要使用oauth2或具有正确写入范围的服务帐户。

答案 1 :(得分:0)

追加和更新需要以下授权范围

https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/spreadsheets

请参见herehere

尝试修改数组中的范围,并在Google控制台的OAuth consent screen中更新应用程序/项目的权限,并在其中添加这些范围。