Create Google Spreadsheet with latest API (v4) in .NET C# in another one's account

3.2k Views Asked by At

I haven't been able to create an Spreadsheet in GoogleDocs using new SpreadSheet API, since it is now supported instead using Google Drive API.

All the examples I've found are for creating and modifying Sheets, not the main spreadsheet.

static string[] Scopes = { SheetsService.Scope.Spreadsheets };

var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets {
    ClientId = clientId, // FROM JSON
    ClientSecret = clientSecret // FROM JSON
},
 Scopes, Environment.UserName, CancellationToken.None,
 new FileDataStore("xxIDxx.GoogleDrive.Auth.Store")).Result;

var service = new SheetsService(new BaseClientService.Initializer() {
    HttpClientInitializer = credential,
    ApplicationName = "Google Sheets API Project",
});

string SpreadSheetID = "AVeryLongAndRandomStringID";
Spreadsheet SpSheet = new Spreadsheet();
SpSheet.Properties = new SpreadsheetProperties();
SpSheet.SpreadsheetId = SpreadSheetID;
SpSheet.Properties.Title = "I HATE THIS SPREADSHEET";

Sheet MySheet = new Sheet();
MySheet.Properties = new SheetProperties();
MySheet.Properties.Title = "MySheet";
MySheet.Properties.SheetId = 34213312;
MySheet.Properties.SheetType = "GRID";

var SheetSet = new List<Sheet>();
SheetSet.Add(MySheet);

SpSheet.Sheets = SheetSet;

var MyNewSpreadSheet = service.Spreadsheets.Create(SpSheet).Execute();

Thanks!

UPDATE:

The small version "var MyNewSpreadSheet" indeed worked (my last attempts also did) but... I haven't realized it was saving the document in MY googleDrive instead my client's account.

What I was trying to accomplish was to create an App where anyone with a google account could create or alter a Spreadsheet document in a "repository" account.

The file "client_secret.json" was generated from my client's account, I don't know why the code creates the Spreadsheet on the logged gmail account.

Any ideas? Thanks!

1

There are 1 best solutions below

1
On

You may want to try sending HTTP request with this format:

POST https://sheets.googleapis.com/v4/spreadsheets

As mentioned in Method: spreadsheets.create, if request is successful, the response body contains a newly created instance of Spreadsheet. Also, please note that using this method requires on of the following OAuth scopes:

  • https://www.googleapis.com/auth/drive
  • https://www.googleapis.com/auth/spreadsheets

Furthermore, please try to also check this documentation if it can help. It's about the Sheets API using C#.