如何使用 google API 将 google 工作表中的过滤行仅获取到 python 脚本?

How to get only filtered rows from google sheets to python script using google API?

我创建了一个 python 脚本,用于在我的 google sheet 上设置过滤器。此筛选按预期工作。我现在有兴趣在设置此过滤器后获取所有行。但是,当我确实接到 api 电话时,我得到了所有行。

我认为我在调用 get 时提供范围是错误的。我以这种格式提供范围 Sheet1!A:J。此范围表示从 A 到 J 列中的所有数据。但是,我不知道如何只提供与过滤数据对应的范围。我在 post (https://sites.google.com/site/scriptsexamples/learn-by-example/google-sheets-api/filters#TOC-Get-filtered-rows) 中描述的 google 应用程序脚本中看到了一个解决方案。然而,这是一个非常低效的解决方案。我不想 运行 对获取的数据进行循环。我想阻止获取所有数据,而宁愿只获取过滤后的数据。 python 脚本可以做到吗?

我目前是这样做的

    # print(json.dumps(body, indent=4))
    resp = service.spreadsheets() \
   .batchUpdate(spreadsheetId=SAMPLE_SPREADSHEET_ID, body=body).execute()

    sheet = service.spreadsheets()
    data = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID, range="Sheet1!A:J").execute()
    print(data)

我相信你的目标如下。

  • 以下是您的回复,

    I meant rows. So for example, I have selected only rows with TEXT_EQ value "Open", I want to fetch all the rows with value "Open" in certain column. Is this clear now or I need to elaborate more?

  • 您想从筛选的 sheet 中检索显示的行。

  • 您正在为 python 使用 googleapis,并且您已经能够使用 Sheets API 获取和放置 Google Spreadsheet 的值].

  • I don't want to run for loop on fetched data. 开始,您希望通过使用脚本进行过滤来实现此目的而无需从所有数据中检索。您只想通过一次 API 调用来实现。

在这种情况下,我想建议使用查询语言来实现您的目标。当使用Query Language时,显示的行可以通过一次调用直接获取。示例脚本如下

示例脚本:

在使用此脚本之前,请设置 Spreadsheet ID 和 sheet ID。并且,此示例脚本使用 credsservice = build('sheets', 'v4', credentials=creds) 来检索访问令牌。所以请附上您的授权脚本。

# In this sample script, the access token is retrieved from "creds".
# service = build('sheets', 'v4', credentials=creds)

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

url = 'https://docs.google.com/spreadsheets/d/' + spreadsheet_id + '/gviz/tq?tqx=out:csv&gid=' + str(sheet_id)
res = requests.get(url, headers={'Authorization': 'Bearer ' + creds.token})
ar = [row for row in csv.reader(io.StringIO(res.text), delimiter=',')]
# ar.pop(0) # When you want to remove the header row, you can also use this.
print(ar)
  • 在此示例中,还使用了 import csvimport ioimport requests

参考: