有没有可能减少函数的这三个部分的运行时间?该函数本身运行良好,但这三个部分加起来超过一秒钟.想知道是否有一种方法可以减少对SpreadSheetApp的调用(通过某种方式结合getSheet和getRange?),或者是否可以更快地从Google Drive加载JSON文件.

var roster = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];

function loadIconDictionary()

var currentCell = sheet.getRange(currentRow, columnMappings[col].sourceCol).getValue();

下面的代码和运行时.如果输入的单元格包括在字典中,该函数只判断编辑,如果包括,它会在该单元格的右侧放置一个图像.图标字典函数加载包含词典的json文件.

//Loads icon if a user fills in a class name
function userEdit(e) {
  console.time('myFunction');
  var sheet = e.source.getActiveSheet();
  var col = e.range.getColumn();
  var roster = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
  console.timeEnd('myFunction');
  // Define the column mappings for your specific case
  var columnMappings = {
    1: { sourceCol: 1, targetCol: 2 },
    7: { sourceCol: 7, targetCol: 8 },
    13: { sourceCol: 13, targetCol: 14 }
  };

  // Check if the edited column is in the mappings
  if (columnMappings[col] && sheet != roster) {
    var currentRow = e.range.getRow();
    var targetCol = columnMappings[col].targetCol;
    console.time('myFunction2');
    if (Object.keys(ICON_DICTIONARY).length === 0) {
      ICON_DICTIONARY = loadIconDictionary(); // Load icon dictionary if not already loaded
    }
    console.timeEnd('myFunction2');
    console.time('myFunction3');
    try {
      var currentCell = sheet.getRange(currentRow, columnMappings[col].sourceCol).getValue();
    } catch(e) {
      Logger.log(e);
    }
    console.timeEnd('myFunction3');
    if (ICON_DICTIONARY.hasOwnProperty(currentCell)) {
      sheet.getRange(currentRow, targetCol).setValue('=IMAGE("' + ICON_DICTIONARY[currentCell] + '")');
    }
    else if (currentCell === "") {
      sheet.getRange(currentRow, targetCol).setValue('');
    }
  }
}

function loadIconDictionary() {
  var fileId = '1Qe_ST11nJIBnPGX_98N0Etd2iHiG70cd'; // Replace with the ID of your file

  // Get the file by ID
  var file = DriveApp.getFileById(fileId);

  if (file) {
    // Convert the blob to a string
    var fileContent = file.getBlob().getDataAsString();

    if (fileContent) {
      try {
        // Parse the content into a JavaScript object (assuming it's JSON)
        var parsedData = JSON.parse(fileContent);

        // Now 'parsedData' contains the content of the file
        return parsedData
      } catch (e) {
        Logger.log('Error parsing file content: ' + e);
      }
    } else {
      Logger.log('File is empty.');
    }
  } else {
    Logger.log('File not found.');
  }
}
Oct 4, 2023, 1:08:24 AM Debug   myFunction: 436ms
Oct 4, 2023, 1:08:24 AM Debug   myFunction2: 406ms
Oct 4, 2023, 1:08:25 AM Debug   myFunction3: 357ms

编辑:一次编辑多个单元格的功能:

//DO NOT CHANGE loadIconDictionary to getIconDictionary, onEdit does not have privileges for DriveApp!
function onEdit(e) { 
  SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Roster");
  var sheet = e.source.getActiveSheet();
  var col = e.range.getColumn();

  // Define the column mappings for your specific case
  var columnMappings = {
    1: { sourceCol: 1, targetCol: 2 },
    7: { sourceCol: 7, targetCol: 8 },
    13: { sourceCol: 13, targetCol: 14 }
  };

  // Check if the edited column is in the mappings
  if (columnMappings[col] && sheet != SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Roster")) {
    var currentRow = e.range.getRow();
    var numRows = 12; // Number of rows to update
    var targetCol = columnMappings[col].targetCol;
    var valuesToSet = [];  
    if (Object.keys(ICON_DICTIONARY).length === 0) {
      ICON_DICTIONARY = getIconDictionary(); // Load icon dictionary if not already loaded
    }
    for (var i = 0; i < numRows; i++) {
      var currentCell = sheet.getRange(currentRow + i, columnMappings[col].sourceCol).getValue();
      var cellValue = '';

      if (ICON_DICTIONARY.hasOwnProperty(currentCell)) {
        cellValue = '=IMAGE("' + ICON_DICTIONARY[currentCell] + '")';
      }
      else if (currentCell != "" || currentCell === false) {
        cellValue = sheet.getRange(currentRow + i, columnMappings[col].targetCol).getValue();
      }

      valuesToSet.push([cellValue]);
    }

    // Set values in a single batch operation
    sheet.getRange(currentRow, targetCol, numRows, 1).setValues(valuesToSet);
  }
}

推荐答案

  1. 获取工作表/范围的延迟通常是由于Electron 表格过多造成的.考虑删除空行、空列.考虑将多个工作表合并为一个工作表.考虑减少冗余数据

  2. try 直接从事件对象获取数据,而不是getActive()个调用.事件对象还在属性rowStartcolumnStart中提供已编辑的行和列信息:

  3. Use JavaScript optimizations like strict mode, consts instead of vars, strict equality checks, , etc

  4. 对于当前行和值,使用offset而不是工作表上的getRange.

  5. try 使用PropertiesService代替Drive文件来存储JSON

/**
 *
 * Loads icon if a user fills in a class name
 * @param {GoogleAppsScript.Events.SheetsOnEdit} e
 */
function userEdit(e) {
  'use strict';
  console.time('myFunction');
  const edRange = e.range;
  const edSheet = edRange.getSheet();
  const edCol = edRange.columnStart;
  //const roster = e.source.getSheets()[0];//use getSheetByName, if you already know the sheet name
  //alternatively, use
  const rosterShName = 'roster';
  console.timeEnd('myFunction');
  // Define the column mappings for your specific case
  const columnMappings = {
    1: { targetCol: 2 },
    7: { targetCol: 8 },
    13: { targetCol: 14 },
  };

  // Check if the edited column is in the mappings
  if (columnMappings[edCol] && edSheet.getName() !== rosterShName) {
    const offset = columnMappings[edCol].targetCol - edCol;
    console.time('myFunction2');
    const ICON_DICTIONARY = loadIconDictionary(); // Load icon dictionary if not already loaded
    console.timeEnd('myFunction2');
    console.time('myFunction3');
    const currentCell = e.value;
    const targetRg = edRange.offset(0, offset);
    if (ICON_DICTIONARY.hasOwnProperty(currentCell)) {
      targetRg.setValue('=IMAGE("' + ICON_DICTIONARY[currentCell] + '")');
    } else if (currentCell === '') {
      targetRg.setValue('');
    }
    console.timeEnd('myFunction3');
  }
}

function loadIconDictionary() {
  const fileId = '1Qe_ST11nJIBnPGX_98N0Etd2iHiG70cd'; // Replace with the ID of your file

  // Get the file by ID
  const file = DriveApp.getFileById(fileId);

  if (file) {
    // Convert the blob to a string
    const fileContent = file.getBlob().getDataAsString();

    if (fileContent) {
      try {
        // Parse the content into a JavaScript object (assuming it's JSON)
        const parsedData = JSON.parse(fileContent);

        // Now 'parsedData' contains the content of the file
        return parsedData;
      } catch (e) {
        Logger.log('Error parsing file content: ' + e);
      }
    } else {
      Logger.log('File is empty.');
    }
  } else {
    Logger.log('File not found.');
  }
}

Javascript相关问答推荐

JavaScript Date对象在UTC中设置为午夜时显示不正确的日期

React存档iframe点击行为

我可以使用CSS有效地实现最大宽度=100%和最大高度=100%,而无需父母有明确的/固定的宽度和高度,替代方法吗?

Next.js(react)使用moment或不使用日期和时间格式

仅针对RTK查询中的未经授权的错误取消maxRetries

在react js中使用react—router—dom中的Link组件,分配的右侧不能被 destruct ''

简单的PayPal按钮集成导致404错误

同一类的所有div';S的模式窗口

如何将zoom 变换应用到我的d3力有向图?

未捕获的运行时错误:调度程序为空

FileReader()不能处理Firefox和GiB文件

不同表的条件API端点Reaction-redux

Django导入问题,无法导入我的应用程序,但我已在设置中安装了它

JavaScript将字符串数字转换为整数

如果我的列有条件,我如何呈现图标?

P5play SecurityError:无法从';窗口';读取命名属性';Add';:阻止具有源的帧访问跨源帧

使用Perl Selify::Remote::Driver执行Java脚本时出错

重新渲染过多(&Q).REACT限制渲染次数以防止无限循环.使用REACT下拉菜单时

如果查询为空,则MongoDB将所有文档与$in匹配

由于http.get,*ngIf的延迟很大