Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimization for alternate background rows color in Google Spreadsheet

I set a different background color for the even rows from the Spreadsheet sheet using Google Apps Script but it is very very very slow...any ideas how can I optimize it?

Example Spreadsheet: https://docs.google.com/spreadsheets/d/1yRotjooCRpuuSTjjgFEzw4xxqPLJwMZJPchYQeNvUyw/edit?usp=sharing

See the GS code by going to Tools -> Script Editor...

This is the code:

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var range = ss.getRange("A1:Z1000");
  ss.setActiveRange(range);
  var totalRows = SpreadsheetApp.getActiveRange().getNumRows();
  var totalColumns = SpreadsheetApp.getActiveRange().getNumColumns();
  var startRow = SpreadsheetApp.getActiveRange().getRow();
  var startColumn = SpreadsheetApp.getActiveRange().getColumn();
  var sheet = SpreadsheetApp.getActiveSheet();
  var row = startRow;
  while (row < totalRows+startRow)
  {
    var column = startColumn;
    while (column < totalColumns+startColumn){
      if(row%2 == 0){
         sheet.getRange(row, column).setBackground("#F3F3F3");
      }
      column++;
    }
    row++;
  }
}
like image 692
Valip Avatar asked Dec 24 '22 04:12

Valip


2 Answers

You can use new applyRowBanding():

Applies a default row banding theme to the range. By default, the banding has header and no footer color.

Example:

function setColors() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var range = ss.getRange("A1:Z1000");
  
  // first remove any existing alternating colors in range to prevent error "Exception: You cannot add alternating background colors to a range that already has alternating background colors."
  range.getBandings().forEach(banding => banding.remove());
  // apply alternate background colors
  range.applyRowBanding();
}

Result:

enter image description here

For more options also see

  • applyRowBanding(bandingTheme)
  • applyRowBanding(bandingTheme, showHeader, showFooter)
like image 165
Kos Avatar answered Mar 15 '23 23:03

Kos


Go line by line instead of cell by cell. You can also loop directly on the lines you want to change.

function setBackgroundColorOnEvenLines() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  var sheet = ss.getActiveSheet();
  var totalRows = sheet.getMaxRows();
  var totalColumns = sheet.getMaxColumns()

  for (var i=2; i <= totalRows; i+=2){
      sheet.getRange(i, 1, 1, totalColumns).setBackground("#F3F3F3");
  }
}

This reference shows how to reference an entire line like above.

like image 43
Mauricio Moraes Avatar answered Mar 15 '23 22:03

Mauricio Moraes