Created
December 29, 2020 06:04
-
-
Save tocalai/6f8e32b1f0001dc3ab638ef1b2e7a2f2 to your computer and use it in GitHub Desktop.
Demonstrate how to use service account to access Google Sheets doc.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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