当前位置:首页 > 未分类 > 正文内容

How to Get Hidden and Filtered Rows in Google Sheets with Google Script

ceacer3周前 (05-02)未分类3954

Hide Rows in Google Sheets

You can hide entire rows in Google Sheets manually or use filters to hide any rows that matches the specified criteria. For instance, if you have a sheet containing orders from different countries, you can set up a country filter to hide all rows where the country is not the United States.

If you have a Google Script that iterates through each row in the Google Sheet for performing actions on the row, like sending emails or merging documents, you can check for the hidden and filtered rows and easily skip them from the workflow.

There are two ways to check for hidden and filtered rows in Google Sheets. You can either use the SpreadsheetApp service of Google Scripts or use the Spreadsheet V4 API.

Check for hidden rows with Google Scripts

function getHiddenAndFilteredRows() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var data = sheet.getDataRange().getValues();
  for (var d = 0; d < data.length; d++) {
    // Row Index starts from 1
    if (sheet.isRowHiddenByFilter(d + 1)) {
      Logger.log('Row #' + d + ' is filtered - value: ' + data[d][0]);
      continue;
    }
    // Row Index starts from 1
    if (sheet.isRowHiddenByUser(d + 1)) {
      Logger.log('Row #' + d + ' is hidden - value: ' + data[d][0]);
      continue;
    }
    // processRow(d)
  }
}

The next example uses (ES6 Chrome V8](/es6-google-apps-script-v8-200206). The script fetches all the rows in the currently active Google Sheet and iterates through each of them to finds all rows that are either hidden or filtered.

/**
 * Get the hidden and filtered rows in the specified Google Sheet
 * @param {string} spreadsheetId - Drive File ID of the Google Spreadsheet
 * @param {string} sheetId - The unique ID of the Google Sheet
 * @returns {Array} Index of the hidden rows (first row's position is 0)
 */
const getHiddenRowsinGoogleSheets = (
  spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId(),
  sheetId = SpreadsheetApp.getActiveSheet().getSheetId()
) => {
  const fields = 'sheets(data(rowMetadata(hiddenByFilter,hiddenByUser)),properties/sheetId)';
  const { sheets } = Sheets.Spreadsheets.get(spreadsheetId, { fields });

  const [sheet] = sheets.filter(({ properties }) => {
    return String(properties.sheetId) === String(sheetId);
  });

  const { data: [{ rowMetadata = [] }] = {} } = sheet;

  const hiddenRows = rowMetadata
    .map(({ hiddenByFilter, hiddenByUser }, index) => {
      return hiddenByUser || hiddenByFilter ? index : -1;
    })
    .filter((rowId) => rowId !== -1);

  return hiddenRows;
};

In order to use the Spreadsheet service in your Google Apps Script project, go to Resources > Advanced Google Services and enable the Google Sheets API.

Alternatively, you may enable the Sheets API directly in your appsscript.json file.

  "dependencies": {
    "enabledAdvancedServices": [{
      "userSymbol": "Sheets",
      "serviceId": "sheets",
      "version": "v4"
    }]
  }

Spreadsheets Quota Limitation

Google Spreadsheets Quota will allow your addon project to make up 100 Spreadsheet reads per 100 seconds and this limit is shared across all users of the project. Thus if your project has too many simultaneous users, the Spreadsheet service may fail with the error:

API call to sheets.spreadsheets.get failed with error: Quota exceeded for quota group 'ReadGroup' and limit 'Read requests per 100 seconds' of service 'sheets.googleapis.com'

To stay withing the quota, you can either cache the results of the expensive getHiddenRows method or use a try-catch block. If the Spreadsheet API fails due to quota error, use the SpreadsheetApp service to check for hidden rows.

Also, a row in the Google Sheet can be filtered and hidden at the same time.

相关文章

How to Automatically Rename Files in Google Drive with Apps Script and AI

How to Automatically Rename Files in Google Drive with Apps Script and AI

Do you have image files in your Google Drive with generic names like IMG_123456.jpg or Screenshot.pn...

Monitor Your Stock Portfolio with Google Sheets and Receive Daily Email Reports

Monitor Your Stock Portfolio with Google Sheets and Receive Daily Email Reports

I have a Stock tracker spreadsheet built inside Google Sheets that keeps track of my fictional stock...

How to Create Personalized Images in Bulk with Google Sheets

How to Create Personalized Images in Bulk with Google Sheets

Yesterday marked Friendship Day, and to celebrate, I sent a personalized image to each of my friends...

Convert Google Docs and Google Sheets with Apps Script

You can easily convert any Google Spreadsheet or Google Document in your Google Drive to other forma...

How Teachers can Email Parents of Students from Google Forms

How Teachers can Email Parents of Students from Google Forms

A school provides email accounts for students that are enrolled in high school. The school has publ...

How to Generate Dynamic QR Codes to Collect Payments through UPI

How to Generate Dynamic QR Codes to Collect Payments through UPI

The BHIM UPI payment system has transformed the way we pay for goods and services in India. You scan...