Fill Google Spreadsheet with Random Data

F
Published in: Google Apps Script - Google Sheets

The spreadSheetFill function will fill the cells of the currently active Google Spreadsheet with random data using Google Scripts. The random values are computed using the Math.random() method.

We could have used the rand() method of Google Spreadsheet directly but the disadvantage is the data will change / refresh every time you open the sheet or edit any cell.

Open the Google Apps Script editor inside the Google Spreadsheet and copy-paste the code. Next choose SpreadSheetFill from the Run menu and authorize.

/* Written by https://gist.github.com/thomaswilburn */

var rowConfig = "timestamp name favorite note season".split(" ");

var rowMapper = function(data) {
  var row = [];
  for (var key in data) {
    var index = rowConfig.indexOf(key);
    if (index > -1) {
      var value;
      if (key in data) {
        value = data[key];
      } else {
        value = "";
      }
      row[index] = data[key];
    }
  }
  for (var i = 0; i < row.length; i++) {
    if (typeof row[i] == "undefined") {
      row[i] = "";
    }
  }
  return row;
}

function spreadSheetFill() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var count = 1000;
  var firstNames = ["Alice", "Bob", "Charles", "Dawn", "Erin", "Fred", "Gwen", "Harry"];
  var lastNames = ["I.", "J.", "K.", "L.", "M.", "N."];
  var getRandom = function(arr) { return arr[Math.floor(Math.random() * arr.length)] };
  for (var i = 0; i < count; i++) {
    var position = Math.PI + (Math.PI / 4) - (Math.random() * Math.PI * .75);
    var distance = 5 * Math.random() + 7;
    var params = {
      timestamp: Date.now(),
      name: getRandom(firstNames) + " " + getRandom(lastNames),
      season: Math.random() > .5 ? true : "",
      favorite: Math.round(Math.random() * 90),
      note: Utilities.base64Encode(Utilities.computeDigest(
          Utilities.DigestAlgorithm.MD5,
          Math.round(Math.random() * 100000000) + "",
          Utilities.Charset.US_ASCII
      ))
    };
    var row = rowMapper(params);
    sheet.appendRow(row);
  }
}
Published in: Google Apps Script - Google Sheets

Looking for something? Find here!

Meet the Author

Web Geek, Tech Columnist
A
Amit Agarwal

Amit Agarwal is a Google Developer Expert in GSuite and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India. Read more on Lifehacker and YourStory

Get in touch