我有一个程序可以验证并可以获取使用GData API的C#实现版本3的所有电子表格列表(它遵循文档中的the example)。我正在弄清楚的是如何通过它的文档密钥获取单个资源。我可以在Google Documents List API中看到大量检索文档列表的示例,我可以看到如何通过exact name search将其归零到特定文档,但我正在尝试生成一些可以在电子表格中生存的代码被重命名。这是我到目前为止编写的代码:
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);
}
}
}
}
答案 0 :(得分:2)
我没有对此进行测试,但根据此https://developers.google.com/gdata/client-cs,您可以使用其网址请求特定条目:
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];
您应该能够检索文档。 如果要将文档保存到HDD,只需添加
即可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));
答案 1 :(得分:2)
我已针对Google.Apis.Drive.v2客户端库nuget软件包版本1.9.2.1890对此进行了测试。但需要注意的一点是,您现在需要通过Google Developer's Console here向您的应用注册开发人员帐户,并为您的应用设置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的情况下完成,您只需要手动枚举电子表格并找到您要查找的电子表格,而不是使用单行代码来完成它。我只是想确保每个人在开始报告之前都知道它不起作用。