Import google spreadsheet data into google forms with app script

后端 未结 3 1876
忘掉有多难
忘掉有多难 2021-02-03 10:50

I searched the internet and I can\'t find a response to this nor the documentation for it. I need to dynamically generate Google forms questions with data from a Google spreadsh

3条回答
  •  攒了一身酷
    2021-02-03 10:59

    In your spreadsheet select Tools > Script Editor and adapt this to your needs:

    /**
       After any change in the sheet, update the combobox options in the Form
    */
    function onChange(e) {
      var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
      var range = sheet.getDataRange();
      var values = range.getValues();
      var comboValues = [];  // <-- cheddar will go here
    
      // in this example we are interested in column 0 and discarding row 1 (the titles)
      for (var i = 1; i <= values.length; i++) {
        var v = values[i] && values[i][0];
        v && comboValues.push(v)
      }
    
      // Sort the values alphabetically, case-insensitive
      comboValues.sort(
        function(a, b) {
          if (a.toLowerCase() < b.toLowerCase()) return -1;
          if (a.toLowerCase() > b.toLowerCase()) return 1;
          return 0;
        }
      );
      Logger.log(comboValues);
    
      // Use your form ID here. You can get it from the URL
      var form = FormApp.openById('');
    
      /* 
        Uncomment this to display the item IDs
        and pick the one that you want to modify
    
      var items = form.getItems();
      for (i = 0; i < items.length; i++) {
        Logger.log("ID: " + items[i].getId(), ': ' + items[i].getType());
      }
      */
      form.getItemById(807137578).asListItem().setChoiceValues(comboValues);
    
    };
    

    To debug, select the script in the combobox and click either "play" or "debug". The first time you will have to give it permissions to interact with your spreadsheet and form.

    Once you are satisfied with the result, in the editor select Resources > Triggers for the active project and add this method to be triggered with any modification on the spreadsheet (on change, not on edit).

    After this, your form options will be changed in real time after any change in your spreadsheet.

提交回复
热议问题