Monday, June 3, 2019

Google Apps Script to delete all the filter views in a spreadsheet

If you have created lots of filter views in a Google Spreadsheet and find it hard to delete all of them one by one manually then you can use the following Google Apps Script code to delete all filter views in one go!

function deleteAllFilterViews() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var id = ss.getId();
 
  var myFilterViews = Sheets.Spreadsheets.get(id, {
    ranges: 'Sheet1',
    fields: 'sheets/filterViews/filterViewId',
  }).sheets[0].filterViews;
 
  Sheets.Spreadsheets.batchUpdate({
    requests: myFilterViews.map(function(e) {
      return { deleteFilterView: { filterId: e['filterViewId'] } };
    }),
  },id);
};

Note:
Paste the above code in the script editor of your spreadsheet and run the function "deleteAllFilterViews"You will need to enable "Google Sheets API", it can be done by navigating to "Resources" > "Advanced Google services..." in the script editor of your spreadsheet.

Also you will need to enable the service in GCP Console:
https://console.cloud.google.com/apis/