Search code examples
c#google-sheetsgdatagoogle-sheets-api

How to export a specific PUBLIC spreadsheet to csv


So I'm trying to export this public sheet to CSV.

I've learnt that I can use the following pattern, simply in my browser (WITHOUT being logged into google):

https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key={0}&exportFormat=csv

This is great and seems rather simply. HOWEVER, when I try to do this in my application, it appears to want me to login. And the login process, I cannot get to work.

I've tried multiple solutions. Using the old auth methods, I managed to get something like this to work:

var spreadsheetService = new SpreadsheetsService(name);

            var csv = string.Empty;
            using (var sr = new StreamReader(spreadsheetService.Query(exportUrl)))
            {
                csv = sr.ReadToEnd();
            }

This worked great, but now credentials have been moved to OAuth and this no longer works for me. I haven't been able to find a way to add the OAuth credentials to this method.

So instead I've tried following the example, and end up with something like this:

    var certificate = new X509Certificate2(data, "notasecret", X509KeyStorageFlags.Exportable);

    var credential = new ServiceAccountCredential(
       new ServiceAccountCredential.Initializer(serviceEmail)
       {
           Scopes = new[] { PlusService.Scope.PlusMe }
       }.FromCertificate(certificate));

    credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Wait();

    var service = new PlusService(new BaseClientService.Initializer()
                                      {
                                          HttpClientInitializer = credential,
                                          ApplicationName = "My app",
                                      });

This does seem to work, but I have no clue what the next step is. How do execute my export query, on the PlusService? Is it even possible? Can I, instead, add the OAuth credentials to the SpreadsheetService?


Solution

  • For downloading a file from Drive and exporting it to csv, you have to use Drive(files.get)then call the export link.

    Also check this documentation to know more about downloading files from Drive.

    Hope that helps!