Data Engineering/Python

[Python/GoogleSpreadSheet API] GoogleSpreadSheet 필터 삽입, 필터 삭제

YSY^ 2023. 9. 16. 19:01

이번 포스팅에서는 구글 스프레드 시트에 필터를 세팅하거나 필터를 삭제하는 방법을 알아보겠습니다.

 

Api 세팅

def api_setting():
    scope = ['https://www.googleapis.com/auth/spreadsheets'
             ,'https://www.googleapis.com/auth/drive']
    json_file_name = 'asset_management_key.json'
    credentials = ServiceAccountCredentials.from_json_keyfile_name(json_file_name, scope)
    gc = gspread.authorize(credentials)
    creds = None
    creds = service_account.Credentials.from_service_account_file(
        json_file_name, scopes=scope
    )

    service = build(
        serviceName="sheets",
        version="v4",
        credentials=creds,
        cache_discovery=False,
        )
    spreadsheets = service.spreadsheets()

    return spreadsheets

BatchUpdate

def batchUpdate(spreadsheets, gsheet_id, requests):
    request_body = {
        'requests': [
            requests
        ]
    }
    print(request_body)
    response = spreadsheets.batchUpdate(
        spreadsheetId=gsheet_id,
        body=request_body
    ).execute()

필터세팅

def set_filter(sheetId):
    requests = {
        'setBasicFilter' : {
            "filter": {
                "range": {
                    "sheetId": sheetId,
                    "startRowIndex" : 0,
                    "startColumnIndex" : 0,
                }

            }
        }
    }

    return requests
        
batchUpdate(spreadsheets, gsheet_id, set_filter(sheetId))

필터 삭제

def clear_filter(sheetId):
    requests = {
        'clearBasicFilter' : {
            'sheetId' : sheetId,
        }
    }

    return requests
 
batchUpdate(spreadsheets, gsheet_id, clear_filter(sheetId))

 

728x90
반응형