How to see excel API results, custom functions in excel sheet(cell) through Script Lab, instead of console log?

被刻印的时光 ゝ 提交于 2019-12-24 07:35:50

问题


I am using Script lab in office 365 and facing difficulty in writing a function which fetches data from API(url). I need help in merging the below code with custom function in Java Script.

from the below code that I am able to get API results in script lab console but I want final results in excel screen(cell). Currently I can see all the ticker.name instead of specific.

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();

For final result I should type =coinmarket.rank(bitcoin) in excel cell and the result should show me the rank of bitcoin from the list of other crypto currencies


回答1:


have you seen this topic?

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

It shows you how to make web request inside custom functions. I'd recommend using Fetch, but it also shows you how to do an XHR request:

/**
 * 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();
  });
}



来源:https://stackoverflow.com/questions/57398925/how-to-see-excel-api-results-custom-functions-in-excel-sheetcell-through-scri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!