使用pythongd批量插入电子表格

2024-10-03 23:25:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用pythongdata在电子表格中填充工作表。问题是,更新单个单元格的速度非常慢。(每次执行一个,每个请求大约需要500毫秒!)因此,我尝试使用gdata中内置的批处理机制来加快速度。在

问题是,我好像不能插入新的细胞。我在网上找过一些例子,但是没有找到。这是我的代码,我根据文档中的一个示例进行了改编。(文档实际上并没有说明如何插入单元格,但它确实说明了如何更新单元格。由于这是新工作表,因此没有单元格。)

此外,启用调试后,我可以看到我的请求返回http200ok。在


import time
import gdata.spreadsheet
import gdata.spreadsheet.service
import gdata.spreadsheets.data

email = '<snip>'
password = '<snip>'
spreadsheet_key = '<snip>'
worksheet_id = 'od6'

spr_client = gdata.spreadsheet.service.SpreadsheetsService()
spr_client.email = email
spr_client.password = password
spr_client.source = 'Example Spreadsheet Writing Application'
spr_client.ProgrammaticLogin()

#  create a cells feed and batch request
cells = spr_client.GetCellsFeed(spreadsheet_key, worksheet_id)
batchRequest = gdata.spreadsheet.SpreadsheetsCellsFeed()

#  create a cell entry
cell_entry = gdata.spreadsheet.SpreadsheetsCell()
cell_entry.cell = gdata.spreadsheet.Cell(inputValue="foo", text="bar", row='1', col='1')

#  add the cell entry to the batch request
batchRequest.AddInsert(cell_entry)

#  submit the batch request
updated = spr_client.ExecuteBatch(batchRequest, cells.GetBatchLink().href)

我的直觉是,我只是误解了API,这应该会随着变化而变化。任何帮助都是非常感谢的。在


Tags: theimportclientemailrequestbatchcellpassword
2条回答

As of Google I/O 2016,最新的Google Sheets API支持批量单元格更新(和读取)。但是请注意,GData与大多数GData-based APIs一起被弃用,包括上面的示例,因为新的API是而不是GData。同样,在代码中将电子邮件地址和密码以纯文本形式存在安全风险,因此new(er) Google APIs使用OAuth2进行授权。你需要得到最新的Google APIs Client Library for Python。这和pip install -U google-api-python-client[或者python3的pip3一样简单。在

至于批插入,这里是一个简单的代码示例。假设rows中有多行数据。要将其大量注入到一个工作表中,比如使用文件ID SHEET_ID&从单元格的左上角开始,可以进行如下调用:

SHEETS.spreadsheets().values().update(spreadsheetId=SHEET_ID, range='A1',
        body={'values': rows}, valueInputOption='RAW').execute()

如果您想要一个较长的示例,请参阅下面的第一个视频,其中这些行是从关系数据库中读取的。对于那些不熟悉这个API的人,这里有来自官方文档的one code sample来帮助你入门。有关更长时间、更多“真实世界”的示例,请参阅以下视频和博客文章:

最新的Sheets API提供了在旧版本中不可用的功能,即让开发人员以编程方式访问工作表,就像使用用户界面一样(创建冻结的行、执行单元格格式、调整行/列的大小、添加透视表、创建图表等)

但是,要对工作表执行文件级访问,例如导入/导出、复制、移动、重命名等,您应该使用Google Drive API。使用驱动器API的示例:

  • 将Google工作表导出为CSV(blogpost
  • “穷人的纯文本到PDF”转换器(blogpost)(*)

(*)-TL;DR:将纯文本文件上载到驱动器,导入/转换为Google Docs格式,然后将该文档导出为PDF。上面的文章使用了driveapiv2;this follow-up post描述了将其迁移到driveapiv3,这里是一个developer video组合了两个“穷人的转换器”帖子。在

我最近也遇到过这种情况(在尝试删除时),但根据文档here来看,批处理insert或{}操作不受支持:

A number of batch operations can be combined into a single request. The two types of batch operations supported are query and update. insert and delete are not supported because the cells feed cannot be used to insert or delete cells. Remember that the worksheets feed must be used to do that.

我不确定您的用例,但是使用ListFeed帮助会有什么帮助吗?它仍然不允许批处理操作,因此会有相关的延迟,但它可能比您现在处理的(或当时)更能忍受。在

相关问题 更多 >