Last active
April 10, 2023 11:31
-
-
Save Rovsau/11e4a07df837aaa4a227c748cc8d6d82 to your computer and use it in GitHub Desktop.
Read data from a public Google Sheet with an API Key (instead of OAuth2)
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 Google.Apis.Services; | |
using Google.Apis.Sheets.v4; | |
using Google.Apis.Sheets.v4.Data; | |
using System.Collections.Generic; | |
using UnityEngine; | |
namespace Rovsau.Unity.Google | |
{ | |
public static class GoogleSheetAPIKeyReader | |
{ | |
// From console.cloud.google.com > Left Menu > APIs and services > Credentials > Create Credentials > API key. | |
private const string apiKey = "AIycAyC38gmLZ1a2_zYMO4Lnxzg2laC7Y0ur_XA"; | |
// From sheet URL. | |
// Sheet must be public. | |
private const string sheetID = "11raBG5B9CKcHOOfg0jUwfRuGQ5Zbswi3dDpcsciKzad"; | |
// Worksheet!Range like Sheet1!A1:X4 | |
private const string readRange = "Output!1:1"; | |
//[InitializeOnLoadMethod] | |
static void Example() | |
{ | |
SheetsService sheetsService = GetSheetsService(apiKey, "Unity Application Name Example"); | |
ReadSheetData(sheetsService, sheetID, readRange); | |
} | |
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."); | |
} | |
}); | |
} | |
private static SheetsService GetSheetsService(string apiKey, string applicationName) | |
{ | |
return new SheetsService(new BaseClientService.Initializer | |
{ | |
ApiKey = apiKey, | |
ApplicationName = applicationName | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment