Last active
April 10, 2023 11:32
-
-
Save Rovsau/6015307d521c2b621e4bb01a37456588 to your computer and use it in GitHub Desktop.
Read and Write data to a private Google Sheet with an OAuth2 (Async)
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 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; | |
using System.Threading.Tasks; | |
namespace Rovsau.Unity.Google | |
{ | |
public class GoogleSheetsOAuth2Async : 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 async void Example() | |
{ | |
string json = Path.Combine(Path.GetDirectoryName(Application.dataPath), jsonKeyFile); | |
SheetsService sheetsService = GetSheetsService(json, "My OAuth2 Example"); | |
await ReadSheetData(sheetsService, sheetID, readRange); | |
List<IList<object>> inputdata = new List<IList<object>>(); | |
inputdata.Add(new List<object> { "This", "is", "my", "input" }); | |
await 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 async Task ReadSheetData(SheetsService sheetsService, string sheetID, string sheetRange) | |
{ | |
SpreadsheetsResource.ValuesResource.GetRequest request = sheetsService.Spreadsheets.Values.Get(sheetID, sheetRange); | |
try | |
{ | |
ValueRange result = await request.ExecuteAsync().ConfigureAwait(false); | |
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."); | |
} | |
} | |
catch (System.Exception ex) | |
{ | |
Debug.Log("Failed to read Google Sheet data: " + ex); | |
} | |
} | |
private static async Task 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; | |
try | |
{ | |
UpdateValuesResponse response = await request.ExecuteAsync().ConfigureAwait(false); | |
Debug.Log("Updated " + response.UpdatedCells + " cells in the Google Sheet"); | |
} | |
catch (System.Exception ex) | |
{ | |
Debug.LogError("Failed to update Google Sheet data: " + ex); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment