我正在尝试使用GDrive REST API .v3导出Google表格并将其保存到Excel格式(实际上是Open Office MIME类型)的本地文件系统中,但无济于事。
我也尝试使用直接链接:
string path1 = "https://drive.google.com/file/d/" + fileId + "/edit?usp=sharing"; //DOESN'T WORK; EXPECTED
string path2 = "https://drive.google.com/uc?export=download&id=" + fileId; //FILE NOT FOUND
string path3 = "https://drive.google.com/open?id=" + fileId; //DOWNLOADS A MESS
string path4 = "https://www.googleapis.com/drive/v3/files/" + fileId + "?alt=media"; //Google API: The remote server returned an error: (403) Forbidden.
WebClient oClient = new WebClient();
oClient.DownloadFile(path4, saveAs);
result = path4;
AND ...
var webcontentlink = "https://drive.google.com/uc?export=download&id=" + fileId;
Google.Apis.Drive.v3.Data.File file =
driveService.Files.Get(fileId).Execute();
var x = driveService.HttpClient.GetByteArrayAsync(webcontentlink);
byte[] arrBytes = x.Result;
File.WriteAllBytes(saveAs, arrBytes);
这是我想要工作的代码:
//GET THE MIME TYPE OF THE GOOGLE FILE
Google.Apis.Drive.v3.Data.File oFile =
driveService.Files.Get(fileId).Execute();
string mimeType = oFile.MimeType;
bool googleDoc = true;
switch (mimeType) {
case "application/vnd.google-apps.document": {
mimeType = "application/vnd.oasis.opendocument.text";
break;
}
case "application/vnd.google-apps.spreadsheet": {
mimeType = "application/x-vnd.oasis.opendocument.spreadsheet";
break;
}
case "application/vnd.google-apps.drawing": {
mimeType = "image/png";
break;
}
case "application/vnd.google-apps.presentation": {
mimeType = "application/pdf";
break;
}
default: {
googleDoc = false;
break;
}
}
var oRequest = driveService.Files.Export(fileId, mimeType);
oRequest.Fields = "*";
MemoryStream stream = new MemoryStream();
oRequest.MediaDownloader.ProgressChanged += (IDownloadProgress progress) =>
{
switch (progress.Status) {
case DownloadStatus.Downloading: {
result = progress.BytesDownloaded.ToString();
break;
}
case DownloadStatus.Completed: {
result = "Export complete.";
break;
}
case DownloadStatus.Failed: {
result = "Export failed.";
break;
}
}
};
oRequest.Download(stream);
SaveStream(stream, saveAs);
private static void SaveStream(MemoryStream stream, string saveAs) {
//PURPOSE: SAVE THE FILE STREAM TO A FILE.
using (FileStream file = new FileStream(saveAs, FileMode.Create, FileAccess.Write)) {
stream.CopyTo(file);
}
}
API示例代码显示为“下载完成”,但是文件内容显示为乱码或空白。我具有正确的MIME类型等,并尝试了几种不同的方法。我希望能够成功地从GDrive导出文件,最好至少将Google表格导出到Excel。这是一个很受欢迎的问题,但似乎没人回答...
答案 0 :(得分:0)
问题是文档(Download Files Guide )中列出的MIME类型不起作用。我确实找到了可以正常工作的MIME类型。以下是测试各种可能的MIME转换类型的详细信息(请参阅每行的注释):
Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details.