Skip to content

Instantly share code, notes, and snippets.

@Rovsau
Last active April 10, 2023 11:32
Show Gist options
  • Save Rovsau/dc681a73547ac32097a853d48f26f2ac to your computer and use it in GitHub Desktop.
Save Rovsau/dc681a73547ac32097a853d48f26f2ac to your computer and use it in GitHub Desktop.
Read and Write data to a private Google Sheet with an OAuth2 (not async)
using System.IO;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace Rovsau.Unity.Google
{
public class GoogleSheetsOAuth2 : MonoBehaviour
{
// From console.cloud.google.com > Left Menu > APIs and services > Credentials > (Select Service Account) > Keys > Add Key > JSON.
// Relative path to the file.
private const string jsonKeyFile = "secrets.json";
// From sheet URL.
private const string sheetID = "11raBG5B9CKcHOOfg0jUwfRuGQ5Zbswi3dDpcsciKzad";
// Worksheet!Range like Sheet1!A1:X4
private const string readRange = "Output!1:1";
private const string writeRange = "Output!4:4";
[InitializeOnLoadMethod]
public static void Example()
{
string json = Path.Combine(Path.GetDirectoryName(Application.dataPath), jsonKeyFile);
SheetsService sheetsService = GetSheetsService(json, "My OAuth2 Example");
// Since these methods are async, but our execution is parallel, the output will come in the opposite order.
// WriteSheetData will finish before ReadSheetData.
ReadSheetData(sheetsService, sheetID, readRange);
List<IList<object>> inputdata = new List<IList<object>>();
inputdata.Add(new List<object> { "This", "is", "my", "input" });
WriteSheetData(sheetsService, sheetID, writeRange, inputdata);
}
public static SheetsService GetSheetsService(string jsonKeyFilePath, string applicationName)
{
GoogleCredential credential = GoogleCredential.FromFile(jsonKeyFilePath).CreateScoped(SheetsService.Scope.Spreadsheets);
return new SheetsService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = applicationName
});
}
private static void ReadSheetData(SheetsService sheetsService, string sheetID, string sheetRange)
{
SpreadsheetsResource.ValuesResource.GetRequest request = sheetsService.Spreadsheets.Values.Get(sheetID, sheetRange);
request.ExecuteAsync().ContinueWith(response =>
{
if (response.IsFaulted)
{
Debug.LogError("Failed to read Google Sheet data: " + response.Exception);
return;
}
ValueRange result = response.Result;
if (result != null && result.Values != null)
{
foreach (IList<object> row in result.Values)
{
Debug.Log(string.Join(", ", row));
}
}
else
{
Debug.LogWarning("No data found in the Google Sheet.");
}
});
}
public static void WriteSheetData(SheetsService sheetsService, string sheetID, string sheetRange, List<IList<object>> data)
{
ValueRange valueRange = new ValueRange
{
Range = sheetRange,
Values = data
};
SpreadsheetsResource.ValuesResource.UpdateRequest request = sheetsService.Spreadsheets.Values.Update(valueRange, sheetID, sheetRange);
request.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;
UpdateValuesResponse response = request.Execute();
Debug.Log("Updated " + response.UpdatedCells + " cells in the Google Sheet");
}
}
}
@Rovsau
Copy link
Author

Rovsau commented Apr 10, 2023

Alternate WriteSheetData (not a real async solution)

public static void WriteSheetData(SheetsService sheetsService, string sheetID, string sheetRange, List<IList<object>> data)
{
    ValueRange valueRange = new ValueRange
    {
        Range = sheetRange,
        Values = data
    };

    SpreadsheetsResource.ValuesResource.UpdateRequest request = sheetsService.Spreadsheets.Values.Update(valueRange, sheetID, sheetRange);

    request.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;

    request.ExecuteAsync().ContinueWith(response =>
    {
        if (response.IsFaulted)//
        {
            Debug.LogError("Failed to update Google Sheet data: " + response.Exception);
        }
        Debug.Log("Updated " + response.Result.UpdatedCells + " cells in the Google Sheet");
    });
}

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