Skip to content

Instantly share code, notes, and snippets.

@yoyu777
Last active March 7, 2024 17:51
Show Gist options
  • Save yoyu777/352f6279b83a19813345ce99293ff6dd to your computer and use it in GitHub Desktop.
Save yoyu777/352f6279b83a19813345ce99293ff6dd to your computer and use it in GitHub Desktop.
sheetreader for Unity (Sheets API v4)
using System;
using System.Collections.Generic;
using Google.Apis.Services;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using UnityEngine;
class SheetReader
{
static private String spreadsheetId = "1vc2kKeLprOJynjUDglqf10ztD7bog";
static private String serviceAccountID = "xxxx@xxxx.iam.gserviceaccount.com";
static private SheetsService service;
static SheetReader()
{
// Loading private key from resources as a TextAsset
String key = Resources.Load<TextAsset>("Creds/key").ToString();
Debug.Log(key);
// Creating a ServiceAccountCredential.Initializer
// ref: https://googleapis.dev/dotnet/Google.Apis.Auth/latest/api/Google.Apis.Auth.OAuth2.ServiceAccountCredential.Initializer.html
ServiceAccountCredential.Initializer initializer=new ServiceAccountCredential.Initializer(serviceAccountID);
// Getting ServiceAccountCredential from the private key
// ref: https://googleapis.dev/dotnet/Google.Apis.Auth/latest/api/Google.Apis.Auth.OAuth2.ServiceAccountCredential.html
ServiceAccountCredential credential = new ServiceAccountCredential(
initializer.FromPrivateKey(key)
);
service = new SheetsService(
new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
}
);
}
public IList<IList<object>> getSheetRange(String sheetNameAndRange)
{
SpreadsheetsResource.ValuesResource.GetRequest request = service.Spreadsheets.Values.Get(spreadsheetId, sheetNameAndRange);
ValueRange response = request.Execute();
IList<IList<object>> values = response.Values;
if (values != null && values.Count > 0)
{
return values;
}
else
{
Debug.Log("No data found.");
return null;
}
}
}
@InsolenceV
Copy link

InsolenceV commented Sep 15, 2023

I had the same problem, for anyone who has it as well I found the following solution:

var credential = (ServiceAccountCredential)GoogleCredential
                .FromFile(path + "/key.json")
                .CreateScoped(SheetsService.Scope.Spreadsheets)
                .UnderlyingCredential;

_service = new SheetsService(new Google.Apis.Services.BaseClientService.Initializer()
{
    HttpClientInitializer = credential
});

I create the credential the following way and pass it to the SheetsService, and all other code remains unchanged.

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