在Google Apps脚本中获取边框详细信息的最佳方法是什么?
我在GAS文档中看不到任何带有边框的内容,因此我不得不求助于Spreadsheet API。
这很好,除了当边框的数量变大时,返回将需要很长时间,或者根本不返回。
有更好的方法吗?
var fieldsBorders = 'sheets(data(rowData/values/userEnteredFormat/borders))';
var currSsId = SpreadsheetApp.getActiveSpreadsheet().getId();
var activeSheet = SpreadsheetApp.getActiveSheet();
var name = activeSheet.getName();
var data = Sheets.Spreadsheets.get(currSsId, {
ranges: name,
fields: fieldsBorders
});
答案 0 :(得分:2)
perhaps it was a bigger sheet it was on, either way 50s is a long time to get the borders. The other calls to GAS take a very small amount of time to complete. Can you confirm this is the only way to get borders?
如果我的理解是正确的,该解决方法如何?在这种解决方法中,我直接请求Sheets API的端点检索边框。
在此示例脚本中,作为示例情况,我假设默认工作表具有26列x 1000行,并且边框设置为所有单元格。
在此示例脚本中,通过一个API调用来检索边框。
var ss = SpreadsheetApp.getActiveSpreadsheet();
var fileId = ss.getId();
var sheetName = ss.getActiveSheet().getName();
var token = ScriptApp.getOAuthToken();
var fields = "sheets/data/rowData/values/userEnteredFormat/borders";
var params = {
method: "get",
headers: {Authorization: "Bearer " + token},
muteHttpExceptions: true,
};
var range = sheetName + "!A1:Z1000";
var url = "https://sheets.googleapis.com/v4/spreadsheets/" + fileId + "?ranges=" + encodeURIComponent(range) + "&fields=" + encodeURIComponent(fields);
var res = UrlFetchApp.fetch(url, params);
var result = JSON.parse(res.getContentText());
结果:
在此示例脚本中,通过多个API调用以异步过程检索边框。
var sep = 500; // Rows retrieving by 1 request.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var fileId = ss.getId();
var sheetName = ss.getActiveSheet().getName();
var token = ScriptApp.getOAuthToken();
var fields = "sheets/data/rowData/values/userEnteredFormat/borders";
var requests = [];
var maxRows = 1000;
var row = 1;
for (var i = 0; i < maxRows / sep; i++) {
var range = sheetName + "!A" + row + ":Z" + (row + sep - 1);
requests.push({
method: "get",
url: "https://sheets.googleapis.com/v4/spreadsheets/" + fileId + "?ranges=" + encodeURIComponent(range) + "&fields=" + encodeURIComponent(fields),
headers: {Authorization: "Bearer " + token},
});
row += sep;
}
var response = UrlFetchApp.fetchAll(requests);
var result = response.reduce(function(ar, e) {
var obj = JSON.parse(e.getContentText());
Array.prototype.push.apply(ar.sheets[0].data[0].rowData, obj.sheets[0].data[0].rowData);
return ar;
}, {sheets: [{data: [{rowData: []}]}]});
结果:
使用示例脚本2时,获得以下结果。
sep
为500(在这种情况下,运行2个API调用。)时,平均处理时间为1.9秒。sep
为200(在这种情况下,运行5个API调用。)时,平均处理时间为1.3秒。但是,如果一次运行的请求数增加,则会发生与配额超过有关的错误。请小心点。