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

如何在Google Sheet中借助OpenAI API根据主题生成完整文章?

解决Google Sheet调用OpenAI API生成文章的问题

代码核心修正与优化

你的代码存在两处关键问题,修正后即可正常获取生成的文章:

  • 替换真实API密钥:将代码中的YOUR_API_KEY替换为你在OpenAI平台获取的有效API密钥。
  • 修正响应解析逻辑:OpenAI Completions接口的返回数据中,生成文本存储在choices数组内,而非原代码中的data字段,这是导致无法获取内容的主要原因。

修正后的完整代码

/**
 * Use GPT-3 to generate an article
 * 
 * @param {string} topic - the topic for the article
 * @return {string} the generated article
 * @customfunction
 */
function getArticle(topic) {
  // 指定API端点和API密钥
  const api_endpoint = 'https://api.openai.com/v1/completions';
  const api_key = '你的真实OpenAI API密钥'; // 替换为个人API密钥

  // 指定API参数,优化prompt确保生成完整文章
  const api_params = {
    prompt: `围绕主题"${topic}"生成一篇结构完整、内容详实的文章`,
    max_tokens: 1024,
    temperature: 0.7,
    model: 'text-davinci-003',
  };

  // 发送API请求,开启异常捕获便于排查问题
  const response = UrlFetchApp.fetch(api_endpoint, {
    method: 'post',
    headers: {
      Authorization: 'Bearer ' + api_key,
      'Content-Type': 'application/json',
    },
    payload: JSON.stringify(api_params),
    muteHttpExceptions: true,
  });

  // 解析响应并返回结果
  const json = JSON.parse(response.getContentText());
  if (json.choices && json.choices.length > 0) {
    return json.choices[0].text.trim(); // 去除文本首尾多余空格
  } else {
    // 返回错误信息辅助排查
    return json.error ? `错误:${json.error.message}` : '未生成对应文章';
  }
}

实际使用步骤

  • 打开Google Sheet,点击「扩展程序」→「Apps脚本」,将原代码替换为修正后的代码,保存并命名项目。
  • 返回Sheet界面,在B列对应单元格输入公式=getArticle(A1)(A1为存储主题的单元格),按下回车即可生成对应文章。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 17:20:58