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

使用Office Script(TypeScript)在Excel调用OpenAI API无输出,求助排查方案

Office Script调用OpenAI API无输出的排查与修复方案

一、先排查基础问题

  • 检查API密钥:确认API工作表B1的密钥无多余空格,且OpenAI账户有可用额度(免费额度到期后需付费)。
  • 检查Prompt工作表B2:确保提示词非空,且是文本格式。
  • 启用调试日志:取消代码中console.log(text)和console.log(arr)的注释,运行后查看Office Script控制台输出,判断是请求失败还是后续处理出错。

二、修复API调用核心问题

1. 替换弃用的模型

text-davinci-002已被OpenAI弃用,改用兼容的gpt-3.5-turbo-instruct模型(仍支持Completion接口)。

2. 添加错误处理逻辑

脚本原本没有异常捕获,一旦请求失败会静默终止。添加try-catch块捕获错误并提示:

// 替换原请求与解析部分
try {
  const response = await fetch(endpoint, {
    method: "POST",
    headers: headers,
    body: body,
  });

  if (!response.ok) {
    throw new Error(`API请求失败: ${response.status} ${response.statusText}`);
  }

  const json = await response.json() as { choices: { text: string }[] };
  const text = json.choices[0].text.trim();
  console.log("API返回结果:", text);

  // 后续输出逻辑...
} catch (error) {
  console.error("错误信息:", error);
  sheet.getRange("B3").setValue(`请求失败: ${(error as Error).message}`);
  return;
}

3. 修正类型与空值校验

确保密钥和提示词是字符串类型,提前拦截空值:

const apiKey = workbook.getWorksheet("API").getRange("B1").getValue() as string;
const mytext = sheet.getRange("B2").getValue() as string;

if (!apiKey || !mytext) {
  sheet.getRange("B3").setValue("请填写API密钥和提示词");
  return;
}

三、优化输出逻辑

直接使用API返回的文本分割,避免从单元格二次读取的冗余步骤:

// 替换原分割写入逻辑
const arr = text.split("\n").filter(line => line.trim().length > 0);
const newcell = result.getRange("A1");
let offset = 0;

arr.forEach(line => {
  newcell.getOffsetRange(offset, 0).setValue(line.trim());
  offset++;
});

sheet.getRange("B3").setValue(offset > 1 ? "查看Result工作表获取多行结果" : "结果已生成");
sheet.getRange("B4").setValue(text);

完整修复后的代码

async function main(workbook: ExcelScript.Workbook) {
  // 获取核心数据
  const apiKey = workbook.getWorksheet("API").getRange("B1").getValue() as string;
  const sheet = workbook.getWorksheet("Prompt");
  const mytext = sheet.getRange("B2").getValue() as string;

  // 基础校验
  if (!apiKey || !mytext) {
    sheet.getRange("B3").setValue("请填写API密钥和提示词");
    return;
  }

  // 初始化结果区域
  const result = workbook.getWorksheet("Result");
  result.getRange("A1:D1000").clear();
  sheet.getRange("B3").setValue("处理中...");

  // API配置
  const endpoint = "https://api.openai.com/v1/completions";
  const model = "gpt-3.5-turbo-instruct";

  // 请求头与请求体
  const headers = new Headers();
  headers.append("Content-Type", "application/json");
  headers.append("Authorization", `Bearer ${apiKey}`);

  const body = JSON.stringify({
    model: model,
    prompt: mytext,
    max_tokens: 1024,
    n: 1,
    temperature: 0.5,
  });

  try {
    // 发送请求并处理响应
    const response = await fetch(endpoint, {
      method: "POST",
      headers: headers,
      body: body,
    });

    if (!response.ok) {
      throw new Error(`HTTP错误: ${response.status} ${response.statusText}`);
    }

    const json = await response.json() as { choices: { text: string }[] };
    const text = json.choices[0].text.trim();
    console.log("API返回内容:", text);

    // 写入结果到Prompt工作表
    sheet.getRange("B4").setValue(text);

    // 分割结果到Result工作表
    const arr = text.split("\n").filter(line => line.trim().length > 0);
    const newcell = result.getRange("A1");
    let offset = 0;

    arr.forEach(line => {
      newcell.getOffsetRange(offset, 0).setValue(line.trim());
      offset++;
    });

    // 更新状态提示
    sheet.getRange("B3").setValue(offset > 1 ? "查看Result工作表获取多行结果" : "结果已生成");
  } catch (error) {
    console.error("错误详情:", error);
    sheet.getRange("B3").setValue(`请求失败: ${(error as Error).message}`);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 03:07:14