我已经针对 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 的情况下完成,您只需要手动枚举电子表格并找到您正在寻找的电子表格,而不是使用一行代码来完成。我只是想确保每个人在开始报告它不起作用之前都知道。