通过Google电子表格迭代 - 如何创建循环?
我是编程的新手。我试图在GSpreadsheets中实现类似的效果,我使用.xls文件(使用openpyxl库)实现了这一效果。这只是简单提醒机器人的一部分,它在.xls或Spreadsheet中发现日期前7天发布提醒(到Slack频道)。 我用Excel示例代码示例:通过Google电子表格迭代 - 如何创建循环?
def excel_check():
zakres = datetime.timedelta(days = 7)
dzisiaj = (datetime.date.today() + zakres)
miesiac = dzisiaj.month
rok = dzisiaj.year
dzien = dzisiaj.day
data_check = datetime.datetime(rok, miesiac, dzien, 0, 0, 0)
wb = load_workbook(filename = "daty.xlsx", data_only = True)
ws = wb.get_sheet_by_name("sheet1")
cell_range = ws["B2":"B25"]
for row in cell_range:
for cell in row:
if cell.value == data_check:
imie = ws.cell(row=cell.row, column=1).value
dzial = ws.cell(row=cell.row, column=3).value
typ_umowy = ws.cell(row=cell.row, column=4).value
przelozony = ws.cell(row=cell.row, column=5).value
AND HERE WE'RE PERFORMING SLACK/API MESSAGE WITH STRINGS ABOVE (imie, dzial, typ_umowy)
我已经成功地改变代码为GSpread行动:
def excel_check():
zakres = datetime.timedelta(days = 7)
dzisiaj = (datetime.date.today() + zakres)
miesiac = dzisiaj.month
rok = dzisiaj.year
dzien = dzisiaj.day
data_check = datetime.datetime(rok, miesiac, dzien, 0, 0, 0)
scope = ["https://spreadsheets.google.com/feeds"]
credentials = ServiceAccountCredentials.from_json_keyfile_name("validcredentialsitworks", scope)
gc = gspread.authorize(credentials)
wks = gc.open_by_url("myurl").sheet1
cell_range = wks.range("B2:B25")
for row in cell_range:
for cell in row:
if cell.value == data_check:
imie = wks.cell(row=cell.row, column=1).value
dzial = wks.cell(row=cell.row, column=3).value
typ_umowy = wks.cell(row=cell.row, column=4).value
AND HERE WE'RE PERFORMING SLACK/API MESSAGE WITH STRINGS ABOVE (imie, dzial, typ_umowy)
不过遗憾的是它并不像Excel的部分上面(Excel的一部分发送正确的消息到Slack,GSpread部分没有)。我有一个错误信息:
TypeError: 'Cell' object is not iterable
这可能出错的语法,但我无法找出什么:(
可否请你给我一个提示
在?总之,什么是等价的:?
for row in cell_range:
for cell in row:
print cell.value
在GSpread
你想使用谷歌表单API将您的数据传递给上述脚本。我跟着these simple steps轻松获取我的数据。一旦你有了,其余的代码应该保持不变。
This is a link to my post其中我解析了电子表格中的数据。如果你需要帮助,你可以参考它。
感谢您的回答。请看看编辑过的问题(我已经添加了一些代码)。我可以连接到我的Gspreadsheet,但其余代码不像Excel部分那样执行。有一个错误消息:TypeError:'单元'对象不可迭代。 – krzostrowski
请通读[this](https://github.com/burnash/gspread)。打印你的cell_range,看看你的列表中的元素是什么,并相应地迭代。我没有亲自使用Gspread。 –
It's probably something wrong with the syntax, but I can't find out what :(
从gspread docs开始,范围方法返回一个单元格列表,而不是行列表。这就是为什么你提到的一个错误:你不能迭代row
,这实际上是一个单元格。
如果你不写到电子表格,从它只是阅读 - 我可能会建议加载它第一个CSV:
with open('wks.csv', 'wb') as out:
out.write(wks.export(format='csv'))
,然后通过一个CSV文件迭代:
import unicodecsv
with open('wks.csv', "rb") as csv_file:
csv_reader = unicodecsv.reader(csv_file, encoding='utf-8', delimiter=',')
你问题得到了解答,但我建议请将您的变量的名称稍微改好一点,如果不是,请评论代码是什么。 –