1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Servicenowでテーブルの最新レコードの一覧をGASで取得し、定期更新する

Last updated at Posted at 2021-08-07

Servicenowを使っていて、テーブル一覧をスプレッドシートに取得し、かつ15分おきに更新して最新の状態を維持したくなったので自分用のメモ。

APIを用いて、シートに既に入っているレコードは更新し、シートに入っていないレコードは新規行を追加する。

何をキーにするか、レコードごとの一意の値を予め決めておく必要があるのは注意。

const ID = "ID";
const TOKEN = "TOKEN";
const ss = SpreadsheetApp.openById("スプレッドシートid");
const sheet = ss.getSheets()[0];
const values = sheet.getDataRange().getValues();
const lastRow = sheet.getLastRow();

function getData() {
  const encoded = encode();
  const headers = {
    "Authorization": " Basic " + encoded
  };
  const options = {
    "method": "get",
    "headers": headers,
    "contentType": "application/json",
  }
  const res = UrlFetchApp.fetch("https://インスタンス名.service-now.com/api/now/table/テーブル名?sysparm_limit=1000", options);
  const resultObjArr = JSON.parse(res.getContentText()).result;
  outerArr = [];
  resultObjArr.forEach(function (data) {
    let innerArr = [
      //ここの配列にカラムの物理名を入れればシートの列がに増える
      data.number,
      data.columnName1,
      data.columnName2,
      data.columnName3,
    ]
    judgeIfUpdateOrInsertAndExcec(sheet, [innerArr])
  });
}


function judgeIfUpdateOrInsertAndExcec(sheet, request) {
  const textFinder = sheet.createTextFinder(`^${request[0][0]}$`).useRegularExpression(true);//[0][xxx]のxxxに、キーにするカラムの列番号を入力する
  const cell = textFinder.findNext();
  if (cell === null) {//新規の時
    sheet.appendRow(request[0]);
  } else {//更新のとき
    let rowNumber = cell.getRow();
    updateRow(sheet, request, rowNumber);
  }
};

function updateRow(sheet, request, rowNumber) {
  sheet.getRange(rowNumber, 1, 1, request[0].length).setValues(request);
};

function encode() {
  let encoded = Utilities.base64Encode(ID + ':' + TOKEN);
  console.log(encoded);
  return encoded;
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?