pyghseets-创建基本过滤器?

时间:2018-07-14 21:57:33

标签: python google-sheets google-sheets-api gspread pygsheets

在pygsheets中,是否可以打开和关闭过滤?我能够将数据框放入工作表中,但是我无法弄清楚如何在不手动进入工作表本身的情况下打开文件管理器。我的数据框将改变大小,默认的过滤器不够智能,无法随数据增长,因此需要我关闭过滤器然后再次打开。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

在Sheets REST API中,删除和/或恢复过滤器非常简单-在调用Requests时可以提供两个spreadsheets#batchUpdate

  1. clearBasicFilter   包括要在其中删除过滤器的工作表ID,例如
    {clearBasicFilter: {sheetId: "someWorkSheetGridId"}}
  2. setBasicFilter

一种避免在标准规范中引入错误的简单方法是,首先查询现有过滤器,然后在以下setBasicFilter请求中使用它。如果不这样做,则需要重新指定过滤条件(如果要还原活动的过滤器)。为了简单地恢复UI的过滤能力,您无需提供criteria属性。

要查询现有的基本过滤器数据,请使用spreadsheets#get和相应的 fields 参数将响应限制为仅包含所需信息:fields: "sheets(properties(sheetId,title),basicFilter)"

使用Google API Python客户端(并忽略任何响应,错误处理等):

def get_existing_basic_filters(wkbkId: str) -> dict:
    params = {'spreadsheetId': wkbkId,
              'fields': 'sheets(properties(sheetId,title),basicFilter)'}
    response = service.spreadsheets().get(**params).execute()
    # Create a sheetId-indexed dict from the result
    filters = {}
    for sheet in response['sheets']:
        if 'basicFilter' in sheet:
            filters[sheet['properties']['sheetId']] = sheet['basicFilter']
    return filters

def clear_filters(wkbkId: str, known_filters: dict):
    requests = []
    for sheetId, filter in known_filters.items():
        requests.append({'clearBasicFilter': {'sheetId': sheetId}})
    if not requests:
        return
    params = {'spreadsheetId': wkbkId,
              'body': {'requests': requests}}
    service.spreadsheets().batchUpdate(**params).execute()

def apply_filters(wkbkId: str, filters: dict):
    # All requests are validated before any are applied, so bundling the set and clear filter
    # operations in the same request would fail: only 1 basic filter can exist at a time.
    clear_filters(wkbkId, filters)

    requests = []
    for sheetId, filter in filters.items():
        # By removing the starting and ending indices from the 'range' property,
        # we ensure the basicFilter will apply to the entire sheet bounds. If one knows the 
        # desired values for startColumnIndex, startRowIndex, endRowIndex, endColumnIndex,
        # then they can be used to create a range-specific basic filter.
        # The 'range' property is a `GridRange`: 
        filter['range'] = {'sheetId': sheetId}
        requests.append({'setBasicFilter': {'filter': filter}})
    if not requests:
        return
    params = {'spreadsheetId': wkbkId,
              'body': {'requests': requests}}
    service.spreadsheets().batchUpdate(**params).execute()

service = get_authed_sheets_service_somehow()
fileId = "some valid Sheets file id"
my_filters = get_existing_basic_filters(fileId)
pprint(my_filters)
###
# do stuff to `my_filters`
###
apply_filters(fileId, my_filters) 

如果有一个updateBasicFilter请求,则可以避免此过程,只需用数据帧的新大小修改现有BasicFilter的范围,但是没有这样的请求。您可能可以根据数据框的大小来确定适合于过滤器GridRange的新范围索引。

您可以考虑尝试Filter Views,看看它们是否对您的情况有用。

资源: