【问题标题】:Unable to access google sheets using api key无法使用 api 密钥访问谷歌表格
【发布时间】:2018-01-22 19:19:21
【问题描述】:

无法使用 v4 .net 客户端库访问谷歌表格,特别是使用更新和附加方法。

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

【问题讨论】:

  • 您将范围设置为 SpreadsheetsReadOnly,也许如果您将其更改为“电子表格”就可以了。

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


【解决方案1】:

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

API 密钥用于访问公共数据。虽然您可以使用它从公开的 Google 表格中读取内容,但您将无法对其进行写入。这可能是由于 api 密钥的授权范围不足。

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

【讨论】:

  • 是的,似乎无法使用 API 密钥编写,虽然我还没有看到任何文档这么说。
  • 我知道你不能上传到谷歌驱动器,这有点道理
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-01
  • 1970-01-01
  • 2016-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多