【问题标题】:Download spreadsheet to CSV with Python and GSpread使用 Python 和 GSpread 将电子表格下载到 CSV
【发布时间】:2021-02-09 01:38:39
【问题描述】:

使用此代码,我可以将电子表格中的所有工作表下载到 csv。 但我只想下载一张表。 有什么办法吗?

代码

import csv
import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)

docid = "123"

client = gspread.authorize(credentials)
spreadsheet = client.open_by_key(docid)
for i, worksheet in enumerate(spreadsheet.worksheets()):
    filename = docid + '-worksheet' + str(i) + '.csv'
    with open(filename, 'wb') as f:
        writer = csv.writer(f)
        writer.writerows(worksheet.get_all_values())

如果有人知道,请告诉我。

From these documents I obtained information

【问题讨论】:

  • “下载工作表”是什么意思?只下载一张表格或下载为 excel 文件而不是 csv?
  • 感谢您的评论。我只想下载一张表并在 csv 中完成。
  • 那你要下载成什么格式?
  • 在我要下载的csv中。
  • 你知道你想要哪张纸吗?您的代码正在为每个工作表制作一个 csv 文件。但我知道你只想要一个。哪一个?

标签: python csv spreadsheet gspread


【解决方案1】:

使用按名称获取工作表的方法应该适合您。

示例(仅打印“sheet2”):

import csv
import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)

docid = "123"

client = gspread.authorize(credentials)
spreadsheet = client.open_by_key(docid)
worksheetName = "sheet2"
worksheet = spreadsheet.worksheet(worksheetName)
filename = docid + '-worksheet' + worksheetName + '.csv'
with open(filename, 'wb') as f:
    writer = csv.writer(f)
    writer.writerows(worksheet.get_all_values())

【讨论】:

  • 如果您只想处理 一个 的情况,为什么还要使用 for 循环?
  • 感谢您可以下载单个电子表格
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-26
  • 2019-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-22
  • 1970-01-01
相关资源
最近更新 更多