以下のデータを含むGoogleSpreadSheetからGoogleFormを作成する。
QuizBody | ChoiceA | ChoiceB | ChoiceC | ChoiceD | Answer | Point |
---|---|---|---|---|---|---|
1+1= | 2 | 4 | 5 | 6 | 2 | 1 |
10+5= | 10 | 12 | 13 | 15 | 15 | 1 |
5+2= | 7 | 4 | 5 | 1 | 7 | 1 |
YOUR_FOLDER_IDはGoogleSpreadSheetファイルが存在するディレクトリ、 YOUR_QUIZ_SHEET_IDはそのファイルのID
const QUIZ_FOLDER_ID = 'YOUR_FOLDER_ID'
const SPREAD_SHEET_ID = 'YOUR_QUIZ_SHEET_ID'
function myFunction() {
const xs = readSpreadSheet()
addFormItems(xs)
}
function readSpreadSheet() {
const spreadSheet = SpreadsheetApp.openById(SPREAD_SHEET_ID)
const sheet = spreadSheet.getSheetByName('data')
const data = sheet.getDataRange().getValues()
const keys = data[0]
const rows = data.filter((e, idx) => {
return idx != 0
})
console.log(rows)
let xs = []
for (const row of rows) {
let myObj = {}
for (const [idx, e] of row.entries()) {
myObj[keys[idx]] = e
}
xs.push(myObj)
}
return xs
}
function addFormItems(xs) {
const formTitle = 'TestQuiz';
const form = FormApp.create(formTitle).setIsQuiz(true)
for (const x of xs) {
const correctAnswers = [x.ChoiceA, x.ChoiceB, x.ChoiceC, x.ChoiceD].map((e, idx) => {
return e === x.Answer
})
const choices = [x.ChoiceA, x.ChoiceB, x.ChoiceC, x.ChoiceD]
const item = form.addMultipleChoiceItem()
const items = choices.map((e, idx) => {
return item.createChoice(e, correctAnswers[idx])
})
const feedback = FormApp.createFeedback().setText(x.FeedbackForIncorrect);
if (x.Link != undefined) {
feedback.addLink(x.Link)
}
item
.setTitle(x.QuizBody)
.setChoices(items).setPoints(x.Point).setRequired(true).setFeedbackForIncorrect(feedback.build())
}
const formFile = DriveApp.getFileById(form.getId())
DriveApp.getFolderById(QUIZ_FOLDER_ID).addFile(formFile)
}
ソースコードをGASのエディタに貼り付け、myfunctionを実行すると
下記のようなフォームが自動生成される。