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

TypeScript如何构造请求调用Google Sheets API追加电子表格数据

TypeScript 构造 Google Sheets API 追加请求方案

前提条件

  • 已获取拥有目标电子表格编辑权限的 OAuth2 访问令牌
  • 已确认目标 spreadsheetId、工作表名称(即range参数值)正确

方案1:使用官方 googleapis 库(推荐)

第一步:安装依赖

npm install googleapis typescript @types/node

第二步:TypeScript 代码实现

import { google } from 'googleapis';

// 配置参数,替换为你自己的实际值
const CONFIG = {
  SPREADSHEET_ID: '你的目标电子表格ID',
  RANGE: '你的目标工作表名称', // 示例值:'Sheet1'
  ACCESS_TOKEN: '你的OAuth2访问令牌',
};

async function appendToSheet() {
  const sheets = google.sheets({ version: 'v4', auth: CONFIG.ACCESS_TOKEN });

  // 要写入的数据和你提供的结构完全一致,无需修改
  const values = [
    ["id", "ser", "IP", "host", "type", "auth"],
    ["1", null, null, "", "Web", ""],
    ["2", null, "191.174.230.02", "", "Proxy", ""]
  ];

  const res = await sheets.spreadsheets.values.append({
    spreadsheetId: CONFIG.SPREADSHEET_ID,
    range: CONFIG.RANGE,
    insertDataOption: 'INSERT_ROWS', // 对应你选择的参数
    valueInputOption: 'RAW', // 对应你选择的参数
    requestBody: { values },
  });

  console.log(`追加成功,共更新${res.data.updates?.updatedRows}行`);
}

appendToSheet().catch(console.error);

方案2:使用原生 Fetch API 手动构造请求(无额外依赖)

直接按照接口规则构造请求即可,代码如下:

// 配置参数,替换为你自己的实际值
const CONFIG = {
  SPREADSHEET_ID: '你的目标电子表格ID',
  RANGE: '你的目标工作表名称', // 示例值:'Sheet1'
  ACCESS_TOKEN: '你的OAuth2访问令牌',
};

async function appendToSheetWithFetch() {
  // 构造请求URL,替换占位符、拼接查询参数
  const url = new URL(
    `https://sheets.googleapis.com/v4/spreadsheets/${CONFIG.SPREADSHEET_ID}/values/${encodeURIComponent(CONFIG.RANGE)}:append`
  );
  url.searchParams.append('insertDataOption', 'INSERT_ROWS');
  url.searchParams.append('valueInputOption', 'RAW');

  // 要写入的数据和你提供的结构完全一致,无需修改
  const requestBody = {
    "values": [
      ["id", "ser", "IP", "host", "type", "auth"],
      ["1", null, null, "", "Web", ""],
      ["2", null, "191.174.230.02", "", "Proxy", ""]
    ]
  };

  const response = await fetch(url.toString(), {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${CONFIG.ACCESS_TOKEN}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(requestBody),
  });

  if (!response.ok) throw new Error(`请求失败:${response.statusText}`);
  const result = await response.json();
  console.log(`追加成功,共更新${result.updates?.updatedRows}行`);
}

appendToSheetWithFetch().catch(console.error);

注意事项

  • 你提供的values结构不需要做任何修改,直接作为请求体的values字段传入即可,null值会自动被解析为空单元格写入
  • range仅需填写工作表名称即可,API会自动定位到该工作表的第一个空行开始追加数据
  • RAW模式下传入的所有内容会原样写入,不会被解析为公式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:39:02