簡體   English   中英

僅使用 Python 和 Google Sheets API 獲取可見數據?

[英]Get only visible data using Python and Google Sheets API?

我正在使用 Google Sheets API 從在線電子表格中檢索數據並將它們讀入 Pandas 數據幀。 我已成功設置腳本以獲取數據,但此默認實現並未考慮我不想返回的隱藏單元格(行或列); 或者,我想過濾掉它們。 到目前為止,我還沒有弄清楚 Google Sheets API 中是否實現了這樣的功能。

我當前的工作實現甚至包括隱藏的行/列:

def getSpreadsheetData(name, spreadsheet_id, sheet_id=None):

    global values_input, service
    creds = ServiceAccountCredentials.from_json_keyfile_name(creds_file_path, SCOPES)
    service = build('sheets', 'v4', credentials=creds)

    sheet = service.spreadsheets()
    data_table = sheet.values().get(spreadsheetId=spreadsheet_id,
                                      range=name).execute()
    data_values = data_table.get('values', [])

    if not data_values:
        print('No data found.')
        return -1

    else:
        df = pd.DataFrame(data_values)
        return df

編輯:這個問題,在我看來,是從單純的過濾基於列值的電子表格,如描述的不同位置 我只想獲取電子表格中未隱藏的那些行。 獲取電子表格內容的默認 API 調用(參見我上面的代碼)獲取所有行,甚至那些手動隱藏的行,因此對於通過鏈接打開電子表格的人來說是不可見的。

關於您的以下目標,

這個問題,在我看來,是從單純的過濾基於列值的電子表格不同,如所描述這里 我只想獲取電子表格中未隱藏的那些行。 獲取電子表格內容的默認 API 調用(參見我上面的代碼)獲取所有行,甚至那些手動隱藏的行,因此對於通過鏈接打開電子表格的人來說是不可見的。

我的示例腳本使用查詢語言從帶有隱藏行的工作表中檢索顯示行。 因此,關於I want to fetch only those rows of a spreadsheet that are not hidden. ,這可以通過示例腳本來實現。 The default API call to fetch content of a spreadsheet (see my code above) fetches all the rows, even those that have manually been hidden and hence are not visible for people opening the spreadsheet via a link. ,我以為您已經嘗試過使用 Sheets API。 在這種情況下,即使隱藏的行存在,也會檢索所有行。

並將read them into a pandas dataframe. ,我以為可以通過修改此答案的示例腳本來實現您的目標。

因此,為了實現您的目標,示例腳本如下。

示例腳本:

service = build('sheets', 'v4', credentials=creds) # This is from your script.

spreadsheet_id = "###" # Please set the Spreadsheet ID.
sheet_id = "###"  # Please set the sheet name.

url = 'https://docs.google.com/spreadsheets/d/' + spreadsheet_id + '/gviz/tq?tqx=out:csv&gid=' + sheet_id
res = requests.get(url, headers={'Authorization': 'Bearer ' + creds.token})
df = pd.read_csv(io.StringIO(res.text), sep=',')
  • 在此示例中,還使用了import csvimport ioimport requests 並且,接入令牌從檢索credsservice = build('sheets', 'v4', credentials=creds)

  • 運行此腳本時,將從帶有隱藏行的工作表中檢索顯示行,並將檢索到的值放入數據框中。

    • 在此示例腳本中,用於將檢索到的值放入數據幀的腳本被添加到腳本中
  • 在這種方法中,不僅可以從帶有手動隱藏行的工作表中檢索顯示行,還可以從帶有基本過濾器過濾行的工作表中檢索顯示行。

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM