Excel sheet 通过 asp.net 核心代码从 google 驱动器下载的格式不正确

Excel sheet downloaded from google drive via asp.net core code is not in correct format

我想使用 ASP.NET 内核从 Google 驱动器下载 Excel sheet。代码有效,但下载文件的格式与云端硬盘上的格式不同。

代码如下:

public async Task<byte[]> DownloadFile(string fileId)
{
    using var ms = new MemoryStream();
    var url = $"https://docs.google.com/spreadsheets/d/{fileId}";

    var scopes = new string[] { DriveService.Scope.Drive, DriveService.Scope.DriveFile, };
    //Using Desktop client Approach
    var clientId = "my client id";
    var clientSecret = "my client secret";
    var secrets = new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret };

    try
    {
        var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(secrets, scopes, "CIS Test Server", CancellationToken.None, new FileDataStore("MyAppsToken")).ConfigureAwait(true);

        using var _service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "Demo App"
        });

        var file = _service.Files.Get(fileId);
        file.MediaDownloader.Download(url, ms);
    }
    catch (Exception ex)
    {
        //log exception
    }

    return ms.ToArray();
}

这是要求的格式:

这是我们得到的结果:

另外,当我们打开下载的文件时会显示一条消息:

Javascript is not enabled on your browser so this file can't be opened enable and reload.

您实际上是在下载实际页面,而不是电子表格本身。

您不能直接下载电子表格,因为它是 Google 文档文件。您需要将其导出为另一种格式(例如 CSV)。为此,您需要使用 var request = _service.Files.Export(fileId, "text/csv") 然后使用 one of the methods available 下载它(例如 DownloadAsync)。显然,您可以根据需要更改 MIME 类型。

参考资料