[英]Import google spreadsheet data into google forms with app script
我搜索了互联网,我找不到对此的回复,也没有找到它的文档。 我需要使用应用程序脚本使用Google电子表格中的数据动态生成Google表单问题,但我不知道如何引用和阅读电子表格。
在电子表格中,选择Tools > Script Editor
,然后根据您的需要进行调整:
/**
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('<my-form-id>');
/*
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);
};
要进行调试,请在组合框中选择脚本,然后单击“播放”或“调试”。 您第一次必须授予其与电子表格和表单进行互动的权限。
对结果感到满意后,在编辑器中Resources > Triggers for the active project
选择Resources > Triggers for the active project
并添加此方法以在电子表格上进行任何修改(在更改时,而不是在编辑时)。
在此之后,您的表单选项将在电子表格中的任何更改后实时更改。
这很简单,请看: https : //developers.google.com/apps-script/guides/sheets#reading
您只需要通过其doc键打开工作表,选择数据并将单元格作为JS对象读取。
这是一个适合我的例子,请检查:
function getSpreadsheetData(sheetId) { // This function gives you an array of objects modeling a worksheet's tabular data, where the first items — column headers — become the property names. var arrayOfArrays = SpreadsheetApp.openById(sheetId).getDataRange().getValues(); var headers = arrayOfArrays.shift(); return arrayOfArrays.map(function (row) { return row.reduce(function (memo, value, index) { if (value) { memo[headers[index]] = value; } return memo; }, {}); }); } function makeOurForm() { var sheetId='input_your_sheet_id' getSpreadsheetData(sheetId).forEach(function (row) { // Set your form template as follows var formName=row.Name // Create your form programmatically, each row means one form var form = FormApp.create(formName) form.setDescription('xxx'); var capitalizedName = row.Name.charAt(0).toUpperCase() + row.Name.slice(1); form.addSectionHeaderItem().setTitle(capitalizedName); var item = form.addMultipleChoiceItem(); item.setTitle('xxx') .setChoices([ item.createChoice('xxx'), ]); form.addParagraphTextItem().setTitle('xxx'); }); }
您可以从网址获取工作表ID,例如:
https://docs.google.com/spreadsheets/d/ YourSheetId / edit#gid = 0
如果您有任何其他问题,请与我们联系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.