Google Apps Script:如何将范围值存入PropertiesService并通过JSON读写对比
批量设置范围属性的实现方法
你可以先一次性读取整个范围的所有值,再遍历生成单元格坐标作为Key存入Properties,比逐单元格读写效率高很多:
function saveRangeProperties() { const sheet = SpreadsheetApp.getActive().getActiveSheet(); // 读取A2:F100整个范围的所有值 const dataRange = sheet.getRange("A2:F100"); const values = dataRange.getValues(); const startRow = dataRange.getRow(); const startCol = dataRange.getColumn(); const props = PropertiesService.getScriptProperties(); const propertiesToSet = {}; values.forEach((row, rowOffset) => { row.forEach((cellValue, colOffset) => { // 生成A1格式的单元格坐标作为Key const colLetter = String.fromCharCode(64 + startCol + colOffset); const cellAddress = `${colLetter}${startRow + rowOffset}`; // 可根据需求选择是否跳过空值存储 if (cellValue !== "") { propertiesToSet[cellAddress] = cellValue; } }); }); // 批量写入属性,避免多次调用setProperty的性能损耗 props.setProperties(propertiesToSet); }
注意1:PropertiesService单次存储的所有属性总大小不能超过9KB,若A2:F100范围数据量较大,建议改用隐藏工作表存储更合适。
注意2:如果需要和ImportRange的动态更新同步,可给saveRangeProperties函数绑定onChange触发器,设置触发条件为表格内容变更时自动运行即可。
读取存储的属性值的方法
读取单个单元格的属性
直接传入A1格式的单元格地址调用即可:
function getCellProperty(cellAddress) { const props = PropertiesService.getScriptProperties(); return props.getProperty(cellAddress); } // 调用示例:获取A2单元格存储的值 const a2Value = getCellProperty("A2");
读取整个A2:F100范围的所有存储属性
返回的二维数组可直接写入工作表使用:
function getRangeProperties() { const props = PropertiesService.getScriptProperties(); const allProps = props.getProperties(); const result = []; // 遍历匹配A2到F100范围内的所有存储属性 for (let row = 2; row <= 100; row++) { const rowData = []; for (let colCode = 65; colCode <= 70; colCode++) { // 65对应A,70对应F const cellAddress = `${String.fromCharCode(colCode)}${row}`; rowData.push(allProps[cellAddress] || ""); } result.push(rowData); } return result; } // 调用示例:将存储的整个范围值写回当前工作表 // const rangeValues = getRangeProperties(); // SpreadsheetApp.getActiveSheet().getRange(2,1,99,6).setValues(rangeValues);
内容的提问来源于stack exchange,提问作者Jim Vl
相关产品推荐
相关产品推荐

