C#-无法在使用Spreadsheet API添加的Google Drive API中获取电子表格

时间:2019-01-05 21:56:16

标签: c# google-sheets google-api google-sheets-api

我有一个项目,我必须在其中添加Google工作表,然后再进行更新。

我能够添加电子表格,这是我正在使用的代码

    public string[] Scopes = { SheetsService.Scope.Spreadsheets };
    static string ApplicationName = "SheetUpdate";

    public SheetsService AuthorizeGoogleApp()
    {
        string fileName = "./credentials.json";
        UserCredential credential;
        using (var stream =
            new FileStream(fileName, FileMode.Open, FileAccess.Read))
        {
            string credPath = "token.json";
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(credPath, true)).Result;
        }
        var service = new SheetsService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName,
        });
        return service;
    }


    public string CreateNewSheet(string sheetTitle)
    {
        var newSheet = new Spreadsheet();
        newSheet.Properties = new SpreadsheetProperties();
        newSheet.Properties.Title = sheetTitle;
        var nsheet = AuthorizeGoogleApp().Spreadsheets.Create(newSheet).Execute();
        return nsheet.SpreadsheetId.ToString();
    }

但是,我需要稍后获取工作表,为此,我必须按名称进行比较以添加相关数据。 但是我没有找到任何使用SheetsService API来获得工作表标题的解决方案。

我可以使用Google Drive API来获取它

    public SpreadsheetsService AuthorizeGoogleDrive()
    {
        string keyFilePath = @"C:\Users\abc\429e5c50bdab.p12";
        string serviceAccountEmail = "xyz@xyz-1546703100663.iam.gserviceaccount.com";
        var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);

        var serviceAccountCredentialInitializer = new ServiceAccountCredential.Initializer(serviceAccountEmail)
        {
            Scopes = new[] { "https://spreadsheets.google.com/feeds" }
        }.FromCertificate(certificate);

        var credential = new ServiceAccountCredential(serviceAccountCredentialInitializer);

        if (!credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Result)
            throw new InvalidOperationException("Access token request failed.");

        var requestFactory = new GDataRequestFactory(null);
        requestFactory.CustomHeaders.Add("Authorization: Bearer " + credential.Token.AccessToken);
        var service = new SpreadsheetsService(null) { RequestFactory = requestFactory };
        return service;
    }

    public void GetSheetByTitle(string title)
    {
        var service = AuthorizeGoogleDrive();

        SpreadsheetQuery query = new SpreadsheetQuery();
        SpreadsheetFeed feed = service.Query(query);

        if (feed.Entries.Count == 0)
        {
            MessageBox.Show("There are no sheets");
        }

        // Iterate through all of the spreadsheets returned and get id by title
        foreach (SpreadsheetEntry sheet in feed.Entries)
        {
            MessageBox.Show(sheet.Title.Text);
            }
        }
  }

问题是,SheetsService正在使用credentials.json,其中包含gmail帐户的凭据,并且工作表已添加到其中,并且SpreadSheetService无法连接(或者我无法连接)使用凭据,并且只能通过使用其他电子邮件的服务帐户进行连接,并且除非与我手动与服务帐户共享,否则工作表将无法用于服务电子邮件。

我正在寻找以下两种解决方案之一:

1-使用SheetsService API

获取工作表标题

2-将两个API都使用相同的帐户(服务帐户或gmail凭据)连接

更新

当我尝试使用凭据连接SpreadSheetService

    public SpreadsheetsService AuthorizeGoogleDrive2()
    {
        var service = new SpreadsheetsService(null);
        service.setUserCredentials("xyz@gmail.com", "***");
        return service;
    }

我得到error execution of authentication request returned unexpected result 404

1 个答案:

答案 0 :(得分:0)

为什么不使用想要的标题提前创建工作表?下面的代码还返回了电子表格ID,供以后使用。我正在将标题和ID记录到一个文件中,以后可以阅读。

try {
    Spreadsheet oBody = new Spreadsheet {
        Properties = new SpreadsheetProperties() {
            Title = sheetTitle,
        },
    };
    SpreadsheetsResource.CreateRequest oRequest = sheetsService.Spreadsheets.Create(oBody);
    Spreadsheet oResponse = oRequest.Execute();
    result = oResponse.SpreadsheetId;
} catch (Exception e) {
    result = "Google API: " + e.Message;
}

参考:https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/create