这是@JSmith'sanswer 的替代实现,使用Sheets REST API 更有效地隐藏和取消隐藏大量工作表。
要从 Apps 脚本使用 Sheets REST API,您首先需要enable it,因为它是“advanced service”。
Sheets API 方法使您能够处理数据的 JavaScript 表示,而无需重复与电子表格服务交互(例如检查每个工作表的名称)。此外,批处理 API 调用作为一个操作处理,因此所有可见性更改同时反映,而电子表格服务的 showSheet() 和 hideSheet() 方法在每次调用后刷新到浏览器。
var MENUSHEET = "Menu";
function onEdit(e) {
if (!e) return; // No running this from the Script Editor.
const edited = e.range,
sheet = edited.getSheet();
if (sheet.getName() === MENUSHEET && edited.getA1Notation() === "A2")
hideUnselected_(e.source, e.value);
}
function hideUnselected_(wb, choice) {
// Get all the sheets' gridids, titles, and hidden state:
const initial = Sheets.Spreadsheets.get(wb.getId(), {
fields: "sheets(properties(hidden,sheetId,title)),spreadsheetId"
});
// Prefixing the choice with `^` ensures "Red" will match "Reddish Balloons" but not "Sacred Texts"
const pattern = new RegExp("^" + choice, "i");
// Construct the batch request.
const rqs = [];
initial.sheets.forEach(function (s) {
// s is a simple object, not an object of type `Sheet` with class methods
// Create the basic request for this sheet, e.g. what to modify and which sheet we are referencing.
var rq = { fields: "hidden", properties: {sheetId: s.properties.sheetId} };
// The menu sheet and any sheet name that matches the pattern should be visible
if (s.properties.title === MENUSHEET || pattern.test(s.properties.title))
rq.properties.hidden = false;
else
rq.properties.hidden = true;
// Only send the request if it would do something.
if ((!!s.properties.hidden) !== (!!rq.properties.hidden))
rqs.push( { updateSheetProperties: rq } );
});
if (rqs.length) {
// Visibility changes will fail if they would hide the last visible sheet, even if a later request in the batch
// would make one visible. Thus, sort the requests such that unhiding comes first.
rqs.sort(function (a, b) { return a.updateSheetProperties.properties.hidden - b.updateSheetProperties.properties.hidden; });
Sheets.Spreadsheets.batchUpdate({requests: rqs}, initial.spreadsheetId);
}
}
在使用 Google 的各种 REST API 时需要熟悉大量资源:
在包含 54 张工作表的工作簿中进行了一些测试,其中我使用 Sheets API 应用了一些更改,并使用 @JSmith 的代码恢复更改,结果表明 API 方法的速度提高了大约 15 倍,使用 console.time & 测量console.timeEnd。 API 更改需要 0.4 到 1.1 秒(平均 1 秒),而电子表格服务方法需要 15 到 42 秒(平均 20 秒)。