一次将循环范围限制为 100 行

Limiting Loop Range to 100 Rows at at time

我有以下脚本,它从我的 Sheet 中获取数据并通过 POST API 调用更新记录;但是一次有 100 个调用的限制,所以我正在寻找一种方法将其添加到我的脚本中(如果可能的话)。我还需要确保发送 header 行 (row1)。所以基本上第一个循环是第 1-101 行,第二个循环是第 1 行和第 102-201 行等。甚至不确定这是可能的

 function updateManyUsers() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  var [headers, ...rows] = sheet.getDataRange().getDisplayValues();
  Logger.log([headers,rows]);
  var users = rows.map(r => {
    var temp = {};
    headers.forEach((h, j) => {
      if (r[j] != "") temp[h] = r[j];
    });
    return temp;
  });
  var url = 'https://redaccted.zendesk.com/api/v2/users/update_many.json';
  var user = 'morris.coyle@redacted_still/token';
 var pwd = 'Every_redacted';
  var options = {
    'method': 'PUT',
    'headers': {
      'Authorization': "Basic " + Utilities.base64Encode(user + ':' + pwd)
    },
    'payload': JSON.stringify({ users }),
    'contentType': 'application/json',
    'muteHttpExceptions': true
  };
  var response = UrlFetchApp.fetch(url, options);
  Logger.log(response.getContentText());
}

提前致谢。

莫兹

描述

我创建了一个简单示例,说明如何从数据中切出 100 行。

我有一个简单的数据集Header plut 256行数据。查看屏幕截图。

屏幕截图

脚本

function updateManyUsers() {
  try {
    let spread = SpreadsheetApp.getActiveSpreadsheet();
    let sheet = spread.getSheetByName("Sheet1");
    let values = sheet.getDataRange().getValues();
    console.log("rows = "+values.length);
    let headers = values.shift();
    let i = 0;
    let numUsers = 100;
    let j = numUsers;
    while( i < values.length ) {
      if( j < values.length ) {
        var users = [].concat(headers,values.slice(i,j));
      }
      else {
        var users = [].concat(headers,values.slice(i));
      }
      console.log("header = "+users[0][0]);
      console.log("users[1] = "+users[1][0]);
      console.log("users[99] = "+users[users.length-1][0]);
      i = i+numUsers;
      j = j+numUsers;
      // Now build your opsions
    }
  }
  catch(err) {
    console.log(err);
  }
}

1:18:04 PM  Notice  Execution started
1:18:05 PM  Info    rows = 257
1:18:05 PM  Info    header = Header
1:18:05 PM  Info    users[1] = 1
1:18:05 PM  Info    users[99] = 100
1:18:05 PM  Info    header = Header
1:18:05 PM  Info    users[1] = 101
1:18:05 PM  Info    users[99] = 200
1:18:05 PM  Info    header = Header
1:18:05 PM  Info    users[1] = 201
1:18:05 PM  Info    users[99] = 256
1:18:05 PM  Notice  Execution completed

参考

我建议制作三个函数:main()get_all_users()update_users() 和 运行 后一个函数以这种方式循环:

function main() {  

  var all_users = get_all_users();

  for (var i = 0; i < all_users.length; i += 100) {
    var users = all_users.slice(i, i + 100);
    update_users(users);
  }
}

function get_all_users() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
  var [headers, ...rows] = sheet.getDataRange().getDisplayValues();
  Logger.log([headers, rows]);
  var users = rows.map((r) => {
    var temp = {};
    headers.forEach((h, j) => { if (r[j] != "") temp[h] = r[j] });
    return temp;
  });
  return users;
}

function update_users(users) {
  var url = "https://redaccted.zendesk.com/api/v2/users/update_many.json";
  var user = "morris.coyle@redacted_still/token";
  var pwd = "Every_redacted";
  var options = {
    method: "PUT",
    headers: {
      Authorization: "Basic " + Utilities.base64Encode(user + ":" + pwd),
    },
    payload: JSON.stringify({ users }),
    contentType: "application/json",
    muteHttpExceptions: true,
  };
  var response = UrlFetchApp.fetch(url, options);
  Logger.log(response.getContentText());
}

让主要功能尽可能简短明了总是一个好主意。并将算法分解为单独的函数,其中每个函数只做一件相对简单的事情:从 sheet 获取用户、发送请求等

你可以尝试这种每 100 次迭代的 for-loop 方法:

function updateManyUsers() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  var data = sheet.getDataRange().getDisplayValues();
  var headers = data.shift(); //remove headers to the array and assign it to headers variable
  for (var i = 0; i < data.length; i += 100){
    var tempArr = data.slice(i, i+100)
    var users = tempArr.map(r => {
      var temp = {};
      headers.forEach((h, j) => {
        if (r[j] != "") temp[h] = r[j];
      });
      return temp;
    });
    var url = 'https://redaccted.zendesk.com/api/v2/users/update_many.json';
    var user = 'morris.coyle@redacted_still/token';
    var pwd = 'Every_redacted';
    var options = {
      'method': 'PUT',
      'headers': {
        'Authorization': "Basic " + Utilities.base64Encode(user + ':' + pwd)
      },
      'payload': JSON.stringify({"users": users }),
      'contentType': 'application/json',
      'muteHttpExceptions': true
    };
    var response = UrlFetchApp.fetch(url, options);
  }  
}

示例数据:

......

每次迭代的变量users内容:

此外,在检查文档时,使用 Update Many Users batch update 时数据格式应如下所示:

{
  "users": [
    { "id": 10071, "name": "New Name", "organization_id": 1 },
    { "id": 12307, "verified": true }
  ]
}