You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Google Apps Script为表格生成的Google表单添加答案键

解决方法

直接调整代码逻辑,让它能识别表格中的正确答案(以红色背景为例),并在生成表单时设置对应的正确选项:

function getDataFromGoogleSheets() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName('test1');
  const range = sheet.getDataRange();
  const values = range.getDisplayValues();
  const backgrounds = range.getBackgrounds(); // 获取单元格背景色
  const questions = [];

  // 从第二行开始遍历,每行对应一个表单问题
  for (let i = 1; i < values.length; i++) {
    const row = values[i];
    const rowBackgrounds = backgrounds[i];
    const title = row[0];
    const options = row.slice(1).filter(opt => opt !== '');
    // 找到红色背景(#ff0000)的选项索引
    const correctIdx = rowBackgrounds.slice(1).findIndex(color => color === '#ff0000');
    const correctAnswer = correctIdx !== -1 ? options[correctIdx] : null;

    questions.push({
      title: title,
      options: options,
      correctAnswer: correctAnswer
    });
  }

  return questions;
}

function myFunction1() {
  const questions = getDataFromGoogleSheets();
  const form = FormApp.create('New Form');

  questions.forEach(question => {
    const item = form.addMultipleChoiceItem()
      .setTitle(question.title)
      .setChoiceValues(question.options)
      .showOtherOption(true);
    
    // 设置正确答案验证
    if (question.correctAnswer) {
      const choices = item.getChoices();
      const correctChoice = choices.find(choice => choice.getValue() === question.correctAnswer);
      if (correctChoice) {
        item.setPoints(1) // 可自定义每题分值
          .setValidation(FormApp.createValidation()
            .setHelpText('请选择正确答案')
            .requireChoiceEquals(correctChoice));
      }
    }
  });
}

关键说明:

  1. 数据读取调整:

    • 按行遍历表格,每行对应一个表单问题
    • 通过单元格背景色识别正确选项,这里默认匹配标准红色#ff0000,如果你的表格用了其他红色色值,直接修改对应颜色代码即可
    • 整理每个问题的标题、选项列表和正确答案
  2. 表单验证设置:

    • 创建选择题后,匹配到正确选项对象,通过setValidation()设置必须选对的规则
    • 可选通过setPoints()给问题设置分值,适配计分需求

内容的提问来源于stack exchange,提问作者seed13

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 21:40:03