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

如何将调用yahoofinanceapi的Java代码转为Apps Script实现表格拉取股票报价

雅虎财经API调用Java转Google Apps Script实现方案

使用前请将代码中的YOUR-PERSONAL-API-KEY替换为你自己的yahoofinanceapi专属API密钥。

完整可运行代码

function getStockPrice() {
  // 获取当前活跃的Google表格
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  // 读取A2单元格的股票代码
  const stockCode = sheet.getRange("A2").getValue().toString().trim();
  if (!stockCode) return;

  // 构造请求参数,对应原Java代码的配置
  const apiUrl = `https://rest.yahoofinanceapi.com/v6/finance/quote/${stockCode}`;
  const options = {
    method: "GET",
    headers: {
      "x-api-key": "YOUR-PERSONAL-API-KEY"
    },
    muteHttpExceptions: true // 方便调试异常情况
  };

  try {
    // 发起请求对应原Java代码的HttpClient.send
    const response = UrlFetchApp.fetch(apiUrl, options);
    const responseData = JSON.parse(response.getContentText());
    // 提取最新股票价格
    const stockPrice = responseData.quoteResponse.result[0].regularMarketPrice;
    // 写入B2单元格
    sheet.getRange("B2").setValue(stockPrice);
  } catch (e) {
    sheet.getRange("B2").setValue("查询失败");
    console.error("请求异常:", e);
  }
}

使用步骤

  • 打开目标Google表格,点击顶部菜单栏「扩展程序」→「Apps Script」进入脚本编辑页面
  • 清空编辑器默认代码,粘贴上述代码,替换API密钥后保存项目
  • 选中getStockPrice函数,点击运行按钮,首次运行需要按提示完成账号授权
  • 授权完成后再次运行函数,回到表格即可看到B2单元格已填充对应股票价格

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:09:03