1

我在 Office 365 中使用脚本实验室,并且在编写从 API(url)获取数据的函数时遇到困难。我需要帮助将以下代码与 Java Script 中的自定义函数合并。

从下面的代码中,我可以在脚本实验室控制台中获得 API 结果,但我希望在 excel 屏幕(单元格)中获得最终结果。目前我可以看到所有的ticker.name 而不是具体的。

var request = new XMLHttpRequest();

request.open("GET", "https://api.coinmarketcap.com/v1/ticker/", true);
request.onload = function() {
  // Begin accessing JSON data here
  var data = JSON.parse(this.response);

  if (request.status >= 200 && request.status < 400) {
    data.forEach((ticker) => {
      console.log(ticker.name, ticker.rank);
    });
  } else {
    console.log("error");
  }
};

request.send();

对于最终结果,我应该在 excel 单元格中输入 =coinmarket.rank(bitcoin),结果应该显示比特币在其他加密货币列表中的排名

4

1 回答 1

0

你看过这个话题吗?

https://docs.microsoft.com/en-us/office/dev/add-ins/excel/custom-functions-web-reqs

它向您展示了如何在自定义函数中发出 Web 请求。我建议使用 Fetch,但它也向您展示了如何执行 XHR 请求:

/**
 * Gets the star count for a given Github organization or user and repository.
 * @customfunction
 * @param userName string name of organization or user.
 * @param repoName string name of the repository.
 * @return number of stars.
 */
async function getStarCount(userName: string, repoName: string) {

  const url = "https://api.github.com/repos/" + userName + "/" + repoName;
  let xhttp = new XMLHttpRequest();

  return new Promise(function(resolve, reject) {
    xhttp.onreadystatechange = function() {
      if (xhttp.readyState !== 4) return;

      if (xhttp.status == 200) {
        resolve(JSON.parse(xhttp.responseText).watchers_count);
      } else {
        reject({
          status: xhttp.status,

          statusText: xhttp.statusText
        });
      }
    };

    xhttp.open("GET", url, true);
    xhttp.send();
  });
}

于 2019-08-07T16:51:10.717 回答