Skip to content

Instantly share code, notes, and snippets.

@tocalai
Created December 29, 2020 06:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tocalai/6f8e32b1f0001dc3ab638ef1b2e7a2f2 to your computer and use it in GitHub Desktop.
Save tocalai/6f8e32b1f0001dc3ab638ef1b2e7a2f2 to your computer and use it in GitHub Desktop.
Demonstrate how to use service account to access Google Sheets doc.
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace SheetsQuickstart
{
class Program
{
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-dotnet-quickstart.json
static string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };
static string ApplicationName = "SheetsLab";
static void Main(string[] args)
{
GoogleCredential credential;
// Put your credentials json file in the root of the solution and make sure copy to output dir property is set to always copy
using (var stream = new FileStream("credentials.json",
FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream).CreateScoped(Scopes);
}
// Create Google Sheets API service.
var service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName
});
// Define request parameters.
String spreadsheetId = "Your sheet id";
String range = "Your sheet name with range";
SpreadsheetsResource.ValuesResource.GetRequest request =
service.Spreadsheets.Values.Get(spreadsheetId, range);
ValueRange response = request.Execute();
IList<IList<Object>> values = response.Values;
if (values != null && values.Count > 0)
{
StringBuilder builder = new StringBuilder();
foreach (var row in values)
{
var rowStr = string.Join(',', row);
builder.AppendLine(rowStr);
}
Console.WriteLine(builder.ToString());
}
else
{
Console.WriteLine("No data found.");
}
Console.Read();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment