Use Google Spreadsheet API to obtain values filtered by Filter view

Viewed 1183

I'm trying to use the Google Sheets API (in PHP using google/apiclient and OAuth 2.0) to get data from a spreadsheet.

This spreadsheet has defined some "Filter views" (defined in Data > Filter views) where for example one of the filter display only rows where the Price column is greater than x.

I'm trying to find a method to get already filtered data using one of the existing Filter views, but I can't find it. Is there any way to do it?

1 Answers

Although I'm not sure about your current script from your question, when you want to retrieve the filtered values from the sheet using the filter view, unfortunately, in the current stage, there are no methods for directly achieving it. So, in this case, it is required to use a workaround. The flow of the workaround is as follows.

Flow of this workaround:

  1. Retrieve the settings of the filter view (filterViews) you want to use.
    • In this case, the method of "spreadsheets.get" can be used.
  2. Create new basic filter to the sheet you want to use using the retrieved settings of the filter view.
    • In this case, the method of "spreadsheets.batchUpdate" can be used.
  3. Retrieve the values of rowMetadata of the sheet.
    • In this case, the method of "spreadsheets.get" can be used.
    • At the values of rowMetadata, the filtered rows have the property of "hiddenByFilter": true,. Using this, you can retrieve the hidden rows and/or the showing rows.
  4. Delete the created basic filter.

By above flow, the filtered values can be retrieved.

Sample script:

When you have already been able to get and put values for Google Spreadsheet using Sheets API with googleapis for PHP, as a sample script of above workaround, you can use the following script.

$service = new Google_Service_Sheets($client); // Please use $client from your script.

$spreadSheetId = '###'; // Please set the Spreadsheet ID.
$sheetName = 'Sheet1'; // Please set the sheet name.
$filterViewName = 'sampleFilter1'; // Please set the filter view name.

// 1. Retrieve the settings of the filter view (`filterViews`) you want to use.
$sheets = $service->spreadsheets->get($spreadSheetId, ["ranges" => [$sheetName], "fields" => "sheets"])->getSheets();
$sheetId = $sheets[0]->getProperties()->getSheetId();
$filterViews = $sheets[0]->getFilterViews();
$filterView = array();
foreach ($filterViews as $i => $f) {
    if ($f->getTitle() == $filterViewName) {
        array_push($filterView, $f);
    };
};
if (count($filterView) == 0) return;

// 2. Create new basic filter to the sheet you want to use using the retrieved settings of the filter view.
$obj = $filterView[0];
$obj['range']['sheetId'] = $sheetId;
$requests = [
    new Google_Service_Sheets_Request(['clearBasicFilter' => ['sheetId' => $sheetId]]),
    new Google_Service_Sheets_Request([
        'setBasicFilter' => [
            'filter' => [
                'criteria' => $obj['criteria'],
                'filterSpecs' => $obj['filterSpecs'],
                'range' => $obj['range'],
                'sortSpecs' => $obj['sortSpecs'],
            ]
        ]
    ])
];
$batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(['requests' => $requests]);
$service->spreadsheets->batchUpdate($spreadSheetId, $batchUpdateRequest);

// 3. Retrieve the values of `rowMetadata` of the sheet.
$sheets = $service->spreadsheets->get($spreadSheetId, ["ranges" => [$sheetName], "fields" => "sheets"])->getSheets();
$rowMetadata = $sheets[0]->getData()[0]->getRowMetadata();
$filteredRows = array(
    'hiddenRows' => array(),
    'showingRows' => array()
);
foreach ($rowMetadata as $i => $r) {
    if (isset($r['hiddenByFilter']) && $r['hiddenByFilter'] === true) {
        array_push($filteredRows['hiddenRows'], $i + 1);
    } else {
        array_push($filteredRows['showingRows'], $i + 1);
    };
};

// 4. Delete the created basic filter.
$requests = [new Google_Service_Sheets_Request(['clearBasicFilter' => ['sheetId' => $sheetId]])];
$batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(['requests' => $requests]);
$service->spreadsheets->batchUpdate($spreadSheetId, $batchUpdateRequest);

print($filteredRows);

Result:

When above script is used for the following sample Spreadsheet,

Before filter view is not set.

enter image description here

After filter view was set.

enter image description here

Result value

From above Spreadsheet, the following result is obtained.

{
  "hiddenRows": [2, 3, 5, 6, 8, 9],
  "showingRows": [1, 4, 7, 10, 11, 12, 13, 14, 15]
}
  • hiddenRows is the hidden row numbers.
  • showingRows is the showingRows row numbers.

Note:

  • IMPORTANT: In this sample script, when the basic filter is used in the sheet, the basic filter is cleared. Please be careful this. When you test this script, please use the sample Spreadsheet.
  • In this sample script, the hidden rows and showing rows are retrieved. Using these values, you can retrieve the filtered values.

References:

Related