Enable data filters on a range with Google Apps Script

后端 未结 3 399
闹比i
闹比i 2020-12-17 01:35

Is there a way to enable data filters by script in a Google Sheet for a certain range? Currently this can be doen manually, but I do not want to select a range, then click \

相关标签:
3条回答
  • 2020-12-17 02:15

    A short answer would be "No". It seems that GAS supports neither getting, nor setting Filter criteria for columns, at least according to this open issue.

    An alternative solution would be to do the filtering and sorting on GAS side, and push the distinct results into different columns or sheets.

    0 讨论(0)
  • 2020-12-17 02:21

    Now you can apply filters using google sheets advanced service. First you need to turn on the Google Sheets API. For that follow the steps as mentioned in the below link:

    https://developers.google.com/sheets/api/quickstart/apps-script

    After that you can use the following function to apply filters.

    function applyFilter() {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var ssId = ss.getId();
      var dataSheet = ss.getActiveSheet();
      var lastRow = dataSheet.getLastRow();
      var lastColumn = dataSheet.getLastColumn();
      var sheetId = dataSheet.getSheetId();
    
      var filterSettings = {
        "range": {
          "sheetId": sheetId,
          "startRowIndex": 0,
          "endRowIndex": lastRow,
          "startColumnIndex": 0,
          "endColumnIndex": lastColumn
        }
      };
      var requests = [{
        "setBasicFilter": {
          "filter": filterSettings
        }
      }];
      Sheets.Spreadsheets.batchUpdate({'requests': requests}, ssId);
    }
    
    0 讨论(0)
  • 2020-12-17 02:37

    Filters are now also available in the native Spreadsheet Service, without needing to activate the Sheets REST API via "Advanced Services".

    The above Sheets REST API method, adapted for native Apps Script:

    function applyFilter() {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var dataSheet = ss.getActiveSheet();
    
      var toFilter = dataSheet.getDataRange();
      var filter = toFilter.createFilter();
    
      // Make some criteria to filter with.
      var fcb = SpreadsheetApp.newFilterCriteria();
      /* use FilterCriteria methods */
      fcb.whenCellNotEmpty();
    
      // Filter the range based on the 1st column:
      filter.setColumnFilterCriteria(1, fcb.build());
    }
    

    Further reading:

    • Filter Reference
    • FilterCriteria Reference
    0 讨论(0)
提交回复
热议问题