Как скачать файл Excel, который был открыт Google Sheets? - PullRequest
1 голос
/ 16 марта 2020

У меня возникли проблемы при загрузке файлов Excel .xlsx с помощью Google Drive Api v3. Я использую следующий код (я использую the. NET SDK ):

using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace DriveQuickstart
{
    class Program
    {
        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/drive-dotnet-quickstart.json
        static string[] Scopes = { DriveService.Scope.Drive };
        static string ApplicationName = "Drive API .NET Quickstart";

        const string FileId = "my_file_id"; //put the ID of the Excel file you want to download here

        public static void Main(string[] args)
        {
            Run().GetAwaiter().GetResult();

            Console.Read();

        }

        private static async Task Run()
        {
            UserCredential credential;

            using (var stream =
                new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

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

            // Define parameters of request.
            FilesResource.GetRequest getRequest = service.Files.Get(FileId);

            using (var stream = new System.IO.FileStream("anExcelFile.xlsx", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite))
            {
                var downloadProgress = await getRequest.DownloadAsync(stream, CancellationToken.None);
                if (downloadProgress.Exception != null)
                {
                    Console.WriteLine(string.Format("We got error {0} {1} {2}", downloadProgress.Exception.Message, Environment.NewLine, downloadProgress.Exception.StackTrace));
                }
                else
                {
                    Console.WriteLine("Download ok");
                }
            }
        }
    }
}

Вы можете легко запустить этот образец, выполнив шаги, описанные здесь . Это работает нормально, однако, как только кто-то открывает файл с Google Sheets и изменяет его, я начинаю видеть следующую ошибку

D2020-03-16 02:10:13.647293 Response[00000007] Response status: InternalServerError 'Internal Server Error'
D2020-03-16 02:10:13.653278 Response[00000007] An abnormal response wasn't handled. Status code is InternalServerError
D2020-03-16 02:10:13.660288 Response[00000007] Abnormal response is being returned. Status Code is InternalServerError
E2020-03-16 02:10:13.667240 Exception occurred while downloading media The service drive has thrown an exception: Google.GoogleApiException: Internal Server Error
   at Google.Apis.Download.MediaDownloader.<DownloadCoreAsync>d__31.MoveNext()

Просмотр информации о файле после того, как он был открыт с Google-листами, я могу видим, что его размер изменен на 0, поэтому я попытался экспортировать его так же, как и для электронной таблицы Google, например:

FilesResource.ExportRequest exportRequest = client.Files.Export(fileId, mimeType);

using (var stream = new System.IO.FileStream(fileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite))
{
    await exportRequest.DownloadAsync(stream, cancellationToken);
}

With mimeType = "application / vnd.openxmlformats-officedocument.spreadsheetml.s.sheet "

Однако затем я запускаю следующую ошибку:

D2020-03-16 01:53:13.512928 Response[00000003] Response status: Forbidden 'Forbidden'
D2020-03-16 01:53:13.520906 Response[00000003] An abnormal response wasn't handled. Status code is Forbidden
D2020-03-16 01:53:13.525911 Response[00000003] Abnormal response is being returned. Status Code is Forbidden
E2020-03-16 01:53:13.538857 Exception occurred while downloading media The service drive has thrown an exception: Google.GoogleApiException: Google.Apis.Requests.RequestError
Export only supports Google Docs. [403]
Errors [
    Message[Export only supports Google Docs.] Location[ - ] Reason[fileNotExportable] Domain[global]
]

   at Google.Apis.Download.MediaDownloader.<DownloadCoreAsync>d__31.MoveNext()

Таким образом, похоже, что ни загрузка, ни экспорт не работают в этом конкретном случае. Что-нибудь еще, что я должен попробовать? Использование webContentLink (https://drive.google.com/uc?id=fileId&export=download) работает нормально (в браузере, который есть), поэтому я предполагаю, что должна быть возможность загрузить файл.

1 Ответ

2 голосов
/ 23 марта 2020

Я поднял проблему в Google, и, похоже, она была исправлена ​​(ср. эта проблема ). Сегодня я попробовал еще раз и, следуя шагам, описанным в исходном вопросе, теперь я вижу, что после того, как файл Excel был отредактирован с помощью листов Google, его размер теперь больше 0 и его можно загрузить.

Файлы который не может быть загружен из-за этой проблемы, похоже, все еще есть та же проблема, но удаление / повторная загрузка вручную эти файлы должны сделать их загружаемыми.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...