How can I set a filter view in a sheets script?

做~自己de王妃 提交于 2019-12-11 20:46:55

问题


I have defined several filter views and would like to apply one of those predefined filter views inside of a Google sheets script.


回答1:


This is a long standing feature request. However, there is no code here in your question to review.

https://code.google.com/p/google-apps-script-issues/issues/detail?id=524

Update

Three additional services have been added to Apps Script related to filters: Class Filter and Range.createFilter, Sheet.getFilter.




回答2:


In below example, a simple criteria TRUE/FALSE is used to filter sheet's view, i.e. if the value in cell is FALSE, the row is hidden. Thus you have two functions, setFilter and clearFilter, apparently. In the most primitive way, this would look something like this:

function setFilter() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var filterSettings = {};

  // The range of data on which you want to apply the filter.
  // optional arguments: startRowIndex, startColumnIndex, endRowIndex, endColumnIndex
  filterSettings.range = {
    sheetId: ss.getSheetByName("sheetName").getSheetId() // provide your sheetname to which you want to apply filter.
  };

  // Criteria for showing/hiding rows in a filter
  // https://developers.google.com/sheets/api/reference/rest/v4/FilterCriteria
  filterSettings.criteria = {};
  var columnIndex = 9; // column that defines criteria [A = 0]
  filterSettings['criteria'][columnIndex] = {
    'hiddenValues': ["FALSE"]
  };

  var request = {
    "setBasicFilter": {
      "filter": filterSettings
    }
  };
  Sheets.Spreadsheets.batchUpdate({'requests': [request]}, ss.getId());
}

function clearFilter() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var ssId = ss.getId();
  var sheetId = ss.getSheetByName("sheetName").getSheetId();
  var requests = [{
    "clearBasicFilter": {
      "sheetId": sheetId
    }
  }];
  Sheets.Spreadsheets.batchUpdate({'requests': requests}, ssId);
}


来源:https://stackoverflow.com/questions/29785482/how-can-i-set-a-filter-view-in-a-sheets-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!