Skip to content

Instantly share code, notes, and snippets.

@bacanu
Last active June 19, 2020 21:25
Show Gist options
  • Save bacanu/0a6d2c0a50db31072fe4b8afe4325ce4 to your computer and use it in GitHub Desktop.
Save bacanu/0a6d2c0a50db31072fe4b8afe4325ce4 to your computer and use it in GitHub Desktop.
Read a random value from a google spreadsheet:
  1. Create a spreadsheet or open an existing one
  2. Get your spreadsheet id. If the spreadsheet has an url like https://docs.google.com/spreadsheets/d/11KRGX-DKhJvWa3rJpVvjWtPQiGKUZnOkrlQ21HKjkU4/edit, the id is 11KRGX-DKhJvWa3rJpVvjWtPQiGKUZnOkrlQ21HKjkU4
  3. Select what data you want to use by picking a range. I suggest a column and the range notation is A:A for column A, B:B for column B and so on.
  4. Go to "Tools > Script Editor"
  5. Replace everything in the file;
    Go from this:
function myFunction() {
  
}

To this:

function doGet() {
  var spreadsheetId = 'REPLACE_WITH_YOUR_SPREADHSHEET_ID';
  var range = 'REPLACE_WITH_YOUR_RANGE'; //ex: A:A will get all the values from the A column.
  var values = Sheets.Spreadsheets.Values.get(spreadsheetId, range).values;
  var value = values[Math.floor(Math.random() * values.length)]
  
  return ContentService.createTextOutput(JSON.stringify(value[0])).setMimeType(ContentService.MimeType.JSON);
}

function doPost() {
  
}

Don't forget to replace you spreasheetId and range in the code above.
6. In the script editor (has an url that starts with https://script.google.com/d) go to resources > advanced google services and search for Google Sheets API;
On the right there is a toggle which is Off by default. You need to turn it on. Click Ok after.
7. In the script editor, go to publish > deploy as web app. Project version is New, Execute the app as Me, Who has access to the app Anyone, even anonymous. Hit deploy.
8. An "Authorization required" popup appears. Click on "Review permissions", choose the account that has access to the spreadsheet. 9. A "This app isn't verified" screen will appear. Click Advanced on the bottom left and then Go to [name] (unsafe).
10. A [Name] wants to access your Google Account consent screen appears that should request access to all your drive account. Click Allow.
11. Returning to the script editor, you have a "current web app URL" which should return a random item from the spreadsheet.

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