google-apps-script - How to reverse engineer Custom Formatting into App Script?
问题描述
Is it possible to reverse engineer Custom Formatting rules that I entered by hand and create an App Script in return?
I would like to generate something like this
var rule = SpreadsheetApp.newConditionalFormatRule()
.whenNumberBetween(1, 10)
.setBackground("#FF0000")
.setRanges([range])
.build();
解决方案
在您的情况下,我认为使用 Sheets API 时,可以简单地创建脚本。
因为在使用 Sheets API 时,条件格式规则的每个设置都可以作为一个对象检索,并且可以使用该对象进行设置。另一方面,当使用电子表格服务(SpreasheetApp)时,需要准备每种设置方法。在这种情况下,我认为脚本可能有点复杂。
因此,在这个答案中,作为实现您目标的一个方向,我想建议将 Sheets API 与 Google Apps Script 一起使用。
示例脚本 1:
此示例脚本从 Google 电子表格中的特定工作表中检索条件格式规则。在使用此脚本之前,请在 Advanced Google services 中启用 Sheets API。
function myFunction1() {
const srcSpreadsheetId = "###"; // Please set the source Spreadsheet ID.
const srcSheetId = "0"; // Please set the source sheet ID.
const obj = Sheets.Spreadsheets.get(srcSpreadsheetId, {fields: "sheets(conditionalFormats,properties)"});
const rules = obj.sheets.reduce((ar, s) => {
if (s.properties.sheetId == srcSheetId && s.conditionalFormats) ar = ar.concat(s.conditionalFormats);
return ar;
}, []);
console.log(JSON.stringify(rules)); // You can see all rules of conditional format rules in the specific sheet of the Spreadsheet.
}
示例脚本 2:
此示例脚本将通过上述示例脚本检索到的条件格式规则设置为 Google 电子表格中的特定工作表。
function myFunction2() {
const rules = [,,,]; // Please set the retrieved conditional format rules.
if (rules.length > 0) {
const dstSpreadsheetId = "###"; // Please set the source Spreadsheet ID.
const dstSheetId = "0"; // Please set the source sheet ID.
const requests = rules.map((rule, i) => {
rule.ranges.forEach(r => r.sheetId = dstSheetId);
return {addConditionalFormatRule: {index: i, rule: rule}};
});
Sheets.Spreadsheets.batchUpdate({requests: requests}, dstSpreadsheetId);
}
}
参考:
推荐阅读
- azure - 通过 Bastion 提供对外部身份以访问 Azure VM 的最佳和最安全的方法是什么?
- flutter - 如何使用 Bloc/Cubit 更新 Flutter 中的列表?
- robotframework - 尝试使用 Robot Framework 中的 SapGuiLibrary 与 SAP 元素交互时出错
- php - 发送大量信息后如何整理我的网址?
- amazon-web-services - 基于标签保护 AWS 资源
- javascript - 根据 if 条件重新排列一行内容
- c# - 如何在 C# 中可靠地启动进程?
- symfony - 如何为子资源启用分页?
- r - 在 for 循环中访问结构元素
- reactjs - 一次使用多个 get 请求 useEffect (react)