Skip to content

Instantly share code, notes, and snippets.

Created July 21, 2015 12:28
What would you like to do?
How to access Google sheet with C# and a service account
var certificate = new X509Certificate2(@"c:\Diamto Test Everything Project.p12", "notasecret", X509KeyStorageFlags.Exportable);
const string user = "";
var serviceAccountCredentialInitializer = new ServiceAccountCredential.Initializer(user) {Scopes = new[] { "" }
var credential = new ServiceAccountCredential(serviceAccountCredentialInitializer);
if (!credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Result)
throw new InvalidOperationException("Access token request failed.");
var requestFactory = new GDataRequestFactory(null);
requestFactory.CustomHeaders.Add("Authorization: Bearer " + credential.Token.AccessToken);
var service = new SpreadsheetsService(null) { RequestFactory = requestFactory };
// Instantiate a SpreadsheetQuery object to retrieve spreadsheets.
SpreadsheetQuery query = new SpreadsheetQuery();
// Make a request to the API and get all spreadsheets.
SpreadsheetFeed feed = service.Query(query);
if (feed.Entries.Count == 0)
Console.WriteLine("There are no sheets");
// Iterate through all of the spreadsheets returned
foreach (SpreadsheetEntry sheet in feed.Entries)
// Print the title of this spreadsheet to the screen
// Make a request to the API to fetch information about all
// worksheets in the spreadsheet.
WorksheetFeed wsFeed = sheet.Worksheets;
// Iterate through each worksheet in the spreadsheet.
foreach (WorksheetEntry entry in wsFeed.Entries)
// Get the worksheet's title, row count, and column count.
string title = entry.Title.Text;
var rowCount = entry.Rows;
var colCount = entry.Cols;
// Print the fetched information to the screen for this worksheet.
Console.WriteLine(title + "- rows:" + rowCount + " cols: " + colCount);
// Create a local representation of the new worksheet.
WorksheetEntry worksheet = new WorksheetEntry();
worksheet.Title.Text = "New Worksheet";
worksheet.Cols = 10;
worksheet.Rows = 20;
// Send the local representation of the worksheet to the API for
// creation. The URL to use here is the worksheet feed URL of our
// spreadsheet.
WorksheetFeed NewwsFeed = sheet.Worksheets;
service.Insert(NewwsFeed, worksheet);
Copy link

ghost commented Oct 14, 2015

Hi, I've got error :{"Error:"invalid_grant", Description:"", Uri:"""}
related to the instruction: RequestAccessTokenAsync

any help?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment