在 Office 脚本中使用外部提取呼叫

此脚本获取有关用户 GitHub 存储库的基本信息。 它演示如何在简单方案中使用 fetch 。 有关使用 fetch 或其他外部调用的详细信息,请阅读 Office 脚本中的外部 API 调用支持。 有关使用 JSON 对象(如 GitHub API 返回的内容)的信息,请阅读 使用 JSON 将数据传入 Office 脚本和从 Office 脚本传递数据

详细了解 GitHub API 参考中使用的 GitHub API。 还可以通过在 Web 浏览器中访问 https://api.github.com/users/{USERNAME}/repos 来查看原始 API 调用输出 (请务必将 {USERNAME} 占位符替换为 GitHub ID) 。

获取存储库信息示例

示例代码:获取有关用户 GitHub 存储库的基本信息

async function main(workbook: ExcelScript.Workbook) {
  // Call the GitHub REST API.
  // Replace the {USERNAME} placeholder with your GitHub username.
  const response = await fetch('https://api.github.com/users/{USERNAME}/repos');
  const repos: Repository[] = await response.json();

  // Create an array to hold the returned values.
  const rows: (string | boolean | number)[][] = [];

  // Convert each repository block into a row.
  for (let repo of repos) {
    rows.push([repo.id, repo.name, repo.license?.name, repo.license?.url]);
  }
  // Create a header row.
  const sheet = workbook.getActiveWorksheet();
  sheet.getRange('A1:D1').setValues([["ID", "Name", "License Name", "License URL"]]);

  // Add the data to the current worksheet, starting at "A2".
  const range = sheet.getRange('A2').getResizedRange(rows.length - 1, rows[0].length - 1);
  range.setValues(rows);
}

// An interface matching the returned JSON for a GitHub repository.
interface Repository {
  name: string,
  id: string,
  license?: License
}

// An interface matching the returned JSON for a GitHub repo license.
interface License {
  name: string,
  url: string
}

培训视频:如何进行外部 API 调用

观看 Sudhi Ramamurthy 在 YouTube 上演练此示例