问题
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