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

如何将HTML动态表格多行数据批量保存至Google Sheet?

批量保存动态表格行数据到Google Sheet解决方案

一、前端JavaScript修改(收集所有行数据)

原教程仅处理单个表单字段,需修改数据收集逻辑,遍历所有动态行并组装成数组:

function handleFormSubmit(e) {
  e.preventDefault();
  
  // 遍历表格所有行,收集数据
  const rows = [];
  document.querySelectorAll('.form-row').forEach(row => {
    const rowData = {
      // 替换为你的表单字段名,确保和输入框的name/选择器对应
      product: row.querySelector('[name="product"]').value.trim(),
      quantity: row.querySelector('[name="quantity"]').value.trim(),
      price: row.querySelector('[name="price"]').value.trim()
    };
    // 跳过全空行(可选)
    if (Object.values(rowData).some(val => val)) {
      rows.push(rowData);
    }
  });

  if (!rows.length) {
    alert('请填写至少一行有效数据');
    return;
  }

  // 发送批量数据到Google脚本
  fetch('你的Google Script部署URL', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ rows })
  })
  .then(res => res.text())
  .then(() => {
    alert('所有行数据已成功保存');
    // 可选:清空所有行的输入框
    document.querySelectorAll('.form-row input').forEach(input => input.value = '');
  })
  .catch(err => {
    console.error('保存失败:', err);
    alert('数据保存失败,请重试');
  });
}

// 绑定表单提交事件
document.getElementById('your-form-id').addEventListener('submit', handleFormSubmit);

注意:动态添加行的代码需保证新行结构与初始行一致(如相同类名.form-row、输入框name属性),否则无法正确收集数据。

二、Google Apps Script修改(批量写入数据)

调整后端脚本,接收前端传来的行数据数组,批量写入工作表:

const SHEET_NAME = 'Sheet1'; // 替换为你的工作表名称
const scriptProp = PropertiesService.getScriptProperties();

function intialSetup() {
  const activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  scriptProp.setProperty('key', activeSpreadsheet.getId());
}

function doPost(e) {
  const lock = LockService.getScriptLock();
  lock.tryLock(10000);

  try {
    const doc = SpreadsheetApp.openById(scriptProp.getProperty('key'));
    const sheet = doc.getSheetByName(SHEET_NAME);

    const requestData = JSON.parse(e.postData.contents);
    const rows = requestData.rows;

    // 组装写入Sheet的二维数组,顺序需与Sheet表头完全对应
    const writeData = rows.map(row => [
      new Date(), // 可选:添加提交时间戳
      row.product,
      row.quantity,
      row.price
      // 按Sheet表头顺序添加其他字段
    ]);

    // 批量追加数据到Sheet末尾
    const nextRow = sheet.getLastRow() + 1;
    sheet.getRange(nextRow, 1, writeData.length, writeData[0].length).setValues(writeData);

    return ContentService
      .createTextOutput(JSON.stringify({ result: 'success' }))
      .setMimeType(ContentService.MimeType.JSON);
  } catch (err) {
    return ContentService
      .createTextOutput(JSON.stringify({ result: 'error', error: err.message }))
      .setMimeType(ContentService.MimeType.JSON);
  } finally {
    lock.releaseLock();
  }
}

部署与验证

  1. 修改完Google Apps Script后,重新部署为Web App,权限设置按需调整(如“任何人,甚至匿名”),并更新前端fetch中的URL。
  2. 测试动态添加多行数据并提交,检查Google Sheet是否所有行都已写入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 06:10:32