Filter Or Hide Row

前端 未结 1 957
一个人的身影
一个人的身影 2021-01-07 08:31

[Back story] I have a Google Sheet I use for emailing schedules to subcontractors. Each subcontractor has their own sheet, and I also have one last sheet ca

相关标签:
1条回答
  • 2021-01-07 09:08

    I had to change one line of your original code, to get it to work:

      sheet.hideRow(sheet.getRange(i,2));  // Operates on a range
    

    With that, I timed it on a test spreadsheet, ~200 rows with an even distribution of true / false cells. The execution transcript reported [4.656 seconds total runtime].

    As you suspected, you can reduce the Service calls by using an array with a set of data (in this case, all of column B). Here's the "hide" method, using an array for testing visibility:

    function MasterFilter() {
      var headers = 4; // # rows to skip
      var sheet = SpreadsheetApp.getActiveSheet();
      var maxRows = sheet.getMaxRows();
    
      //show all the rows
      sheet.showRows(1, maxRows);
    
      //get data from column B
      var data = sheet.getRange('B:B').getValues();
    
      //iterate over all rows
      for(var i=headers; i< data.length; i++){
        if(data[i][0] == false){
          sheet.hideRow(sheet.getRange(i+1,1));
        }
      }
    }
    

    According to the execution transcript, this took [0.106 seconds total runtime] for the test sheet. Watching the screen, it looked like 3 or 4 seconds by the time it refreshed.

    Here's another way to do it. In this one, we read all the data on the Master Sheet, then use Array.filter() to reduce the two-dimensional array to just the rows with true in column B. This smaller set is then written to the Master Sheet, after we clear all previous contents. This cut the execution time in half, [0.059 seconds total runtime] according to the execution transcript. Once again, delays in the refresh of the viewed copy made it look like a couple of seconds.

    // Evaluation function for Array.filter()
    function isVisible(row) {
      return (row[1] === true);  // Check column B
    }
    
    function MasterFilter2() {
      var headers = 4; // # rows to skip
      var sheet = SpreadsheetApp.getActiveSheet();
      var data = sheet.getDataRange().getValues();
      var headerData = data.splice(0,headers); // Skip header rows
      var filteredData = data.filter( isVisible );
      var outputData = headerData.concat(filteredData);  // Put headers back
    
      sheet.clearContents();  // Clear content, keep format
    
      // Save filtered values
      sheet.getRange(1, 1, outputData.length, outputData[0].length).setValues(outputData); 
    }
    
    0 讨论(0)
提交回复
热议问题