Google Spreadsheet is a powerful tool that allows users to organize, analyze and share data using a web-based spreadsheet application. One of the most common tasks when working with spreadsheets is formatting the data in a way that is easy to read and visually appealing. In this article, we’ll show you how to use Google Apps Script to alternate row colors in a Google Spreadsheet.

Step 1: Create a new Google Spreadsheet

First, create a new spreadsheet by opening Google Sheets and clicking on “Blank” to create a new sheet.

Step 2: Set up the header row

The header row is the first row of the spreadsheet that contains the column names. It’s important to format this row separately from the data rows so that it stands out.

  • Select the first row of the spreadsheet.
  • Right-click and select “Row height” to adjust the height of the row to fit the text.
  • Click on the “Fill color” icon and select a color for the header row.

Step 3: Set up the data range

The data range is the section of the spreadsheet where the data will be displayed. It’s important to define this range so that the script knows where to apply the formatting.

  • Click on the top-left cell of the data range.
  • Hold down the Shift key and click on the bottom-right cell of the data range.
  • Note the cell range in the top-left corner of the window (e.g. A2:C10).

Step 4: Write the script

We will use Google Apps Script to apply alternating colors to the data rows.

  • Open the script editor by clicking on “Tools” and selecting “Script editor…”
  • Delete any existing code in the script editor.
  • Copy and paste the following code into the script editor:
// Set the starting row and column of the data range
var startRow = 2; // skip the header row
var startCol = 1;

// Get the number of rows and columns in the data range
var numRows = sheet.getLastRow() - startRow + 1;
var numCols = sheet.getLastColumn() - startCol + 1;

// Alternate row colors
for (var i = 0; i < numRows; i++) {
    if (i % 2 == 0) {
        sheet.getRange(startRow + i, startCol, 1, numCols).setBackground("#f2f2f2");
    } else {
        sheet.getRange(startRow + i, startCol, 1, numCols).setBackground("#ffffff");

This script will alternate row colors starting from the data row immediately after the header row.

Step 5: Run the script

  • Save the script by clicking on “File” and selecting “Save”.
  • Click on the “Run” button to run the script for the first time.
  • Follow the prompts to grant permission for the script to access your Google Sheets data.
  • Refresh the spreadsheet to see the formatting changes.

Congratulations! You’ve successfully written a script that applies alternating row colors to a Google Spreadsheet.