2

我有一个程序可以进行身份​​验证,并且可以获取使用 GData API 的 C# 实现版本 3 的所有电子表格的列表(它遵循文档中的示例)。我很难弄清楚如何通过它的文档键获取单个资源。我可以在Google Documents List API中看到很多检索文档列表的示例,并且我可以看到如何通过精确名称搜索将特定文档归零,但我正在尝试生成一些在电子表格被重命名后仍然存在的代码。这是我到目前为止编写的代码:

using System;
using Google.GData.Client;
using Google.GData.Spreadsheets;
using Microsoft.VisualBasic;

namespace q14201622
{
  class Program
  {
    static void Main(string[] args)
    {
      //OAuth 2 Stuff
      var parameters = new OAuth2Parameters() {
        ClientId = CLIENT_ID,
        ClientSecret = CLIENT_SECRET,
        RedirectUri = REDIRECT_URI,
        Scope = SCOPE
      };
      Process.Start(OAuthUtil.CreateOAuth2AuthorizationUrl(parameters));
      var response = Interaction.InputBox("Enter oAuth Code:", "q14201622", "", 0, 0);
      parameters.AccessCode = response;
      OAuthUtil.GetAccessToken(parameters);
      var accessToken = parameters.AccessToken;

      //Fetch Documents
      var requestFactory = new GOAuth2RequestFactory(null, "q14201622-v1", parameters);
      var service = new SpreadsheetsService("q14201622-v1");
      var query = new SpreadsheetQuery();
      query.Title = "Exact Title";
      query.Exact = true;

      //Iterate over the results
      var feed = service.Query(query);
      foreach (var entry in feed.Entries)
      {
        Console.WriteLine(entry.Id + ":"+ entry.Title.Text);
      }
    }
  }
}
4

2 回答 2

2

我已经针对 Google.Apis.Drive.v2 客户端库 nuget 包版本 1.9.2.1890 对此进行了测试。但是,需要注意的一点是,您现在需要使用 Google API 注册开发人员帐户,并通过此处的 Google 开发人员控制台为您的应用程序设置 API 访问权限和凭据。

如果您只想将其用于服务帐户,也就是不代表用户访问文件,而是用于自动化或内部工具,请使用以下内容:

(如果我没记错的话,服务帐户仍然需要人工通过 OAuth 浏览器弹出窗口进行一次性 OAuth 批准交互,以将应用程序添加到服务帐户上的授权应用程序中)

private const string SERVICE_ACCOUNT_EMAIL = "YOUR_SERVICE_ACCOUNT_EMAIL_HERE"; //looks like XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX@developer.gserviceaccount.com;

static DriveService BuildServiceAccountService()
{
  var certificate = new X509Certificate2(PATH_TO_YOUR_X509_CERT,
      "notasecret", X509KeyStorageFlags.Exportable);
  var credential = new ServiceAccountCredential(
      new ServiceAccountCredential.Initializer(SERVICE_ACCOUNT_EMAIL)
      {
          Scopes = new[] { DriveService.Scope.Drive },
          User = "ACTUAL_EMAIL_ADDRESS" // this should be the normal xxxxxx@gmail account that has the google drive files
      }.FromCertificate(certificate));

  // Create the service.
  var service = new DriveService(new BaseClientService.Initializer()
  {
      HttpClientInitializer = credential,
      ApplicationName = "Drive API Service Account Sample",
  });

  return service;
}

public static void DownloadSpreadsheetAsXlsx(string spreadsheetName, string filePath)
{
  var service = BuildServiceAccountService();
  var request = service.Files.List();
  request.Q = String.Format("title = '{0}'", spreadsheetName);
  var files = request.Execute();
  var file = files.Items.FirstOrDefault();

  var dlUrl = String.Format("https://docs.google.com/spreadsheets/d/{0}/export?format=xlsx&id={0}", file.Id);

  File.WriteAllBytes(filePath, service.HttpClient.GetByteArrayAsync(dlUrl).Result);
}

要代表用户访问文件,您将需要这样的东西来构建您的服务:

static DriveService BuildUserAccountService(string userEmail)
{
  UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
  new ClientSecrets
  {
     ClientId = "YOUR_CLIENT_ID", // your client Id
     ClientSecret = "YOUR_CLIENT_SECRET", // Your client secret
  },
  new[] { DriveService.Scope.Drive },
  userEmail,
  CancellationToken.None).Result;

  // Create the service.
  var service = new DriveService(new BaseClientService.Initializer()
  {
      HttpClientInitializer = credential,
      ApplicationName = "Drive API User Account Sample",
  });

  return service;
}

为后代着想的旧答案(旧的 Google GData API 已被弃用,低于此点的任何内容都不再相关,不应期望工作):

我在查找文档密钥时遇到了同样的问题。我最终在 AlternateUri 中找到了它。这是我所做的(这已被编译并确认可以在新项目中工作并使用 NuGet 添加 GData.Spreadsheets):

//Use your authentication method here:    
SpreadsheetsService service = new SpreadsheetsService("DownloadSpreadsheet");
service.setUserCredentials("your username", "your password");

SpreadsheetQuery query = new SpreadsheetQuery();
SpreadsheetFeed feed = service.Query(query);
SpreadsheetEntry fileEntry = feed.Entries.Cast<SpreadsheetEntry>().FirstOrDefault(entry => entry.Title.Text == "Name of spreadsheet");

//This is the good part
string key = fileEntry.AlternateUri.Content.Substring(fileEntry.AlternateUri.Content.IndexOf("?key="));
string dlUrl = "https://docs.google.com/feeds/download/spreadsheets/Export" + key + "&exportFormat=xlsx&format=xlsx";
Stream stream = service.Query(new Uri(dlUrl));
using (FileStream fstream = new FileStream("something.xlsx", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
{
    stream.CopyTo(fstream);
    fstream.Flush();
}

我应该提一下,由于.Cast<SpreadsheetEntry>().FirstOrDefault()线路原因,这需要 LINQ(.NET Framework 3.5 或更高版本)。这可以在没有 LINQ 的情况下完成,您只需要手动枚举电子表格并找到您正在寻找的电子表格,而不是使用一行代码来完成。我只是想确保每个人在开始报告它不起作用之前都知道。

于 2013-06-18T00:17:19.950 回答
2

我没有对此进行测试,但根据此https://developers.google.com/gdata/client-cs您可以使用其 URL 请求特定条目:

FeedQuery singleQuery = new FeedQuery();
singleQuery.Uri = new Uri(newEntry.SelfUri.ToString()); 
AtomFeed newFeed = service.Query(singleQuery);
AtomEntry retrievedEntry = newFeed.Entries[0];    

现在,如果你有文档密钥,你也有 URL (https://docs.google.com/spreadsheet/ccc?key=[insert key here]) 你可以使用一个简单的

string docKey = "nice doc key";
string  gDocsURL = "https://docs.google.com/spreadsheet/ccc?key={0}";
string docURL = String.Format(gDocsURL,docKey);

接着

FeedQuery singleQuery = new FeedQuery();
singleQuery.Uri = new Uri(docURL); 
AtomFeed newFeed = service.Query(singleQuery);
AtomEntry retrievedEntry = newFeed.Entries[0];  

您应该能够检索文档。如果要将文档保存到硬盘,只需添加

string docFormat ="xlsx";// or xls or csv or pdf etc.
string gDocsDownloadURL="https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key={0}&exportFormat={1}"
string downloadUrl = String.format(gDocsDownloadURL,docKey,docFormat);
Stream stream = service.Query(new Uri(downloadUrl));
于 2013-01-07T20:49:49.570 回答