[英]python / gspread - How to update a range of cells with a data list?
I have a data list (extracted from CSV) and I'm trying to use Python / GSpread to update a range of cells on a Google Doc. 我有一个数据列表(从CSV中提取),并且正在尝试使用Python / GSpread更新Google文档上的一系列单元格。 Here is my code sample:
这是我的代码示例:
import gspread
def write_spreadsheet(spreadsheet_name, sheet_id, data, start_row):
gc = gspread.login('yourmail@gmail.com', 'password')
wks = gc.open(spreadsheet_name).get_worksheet(sheet_index)
start_letter = 'A'
end_letter = string.uppercase[len(data[0]) - 1]
end_row = start_row + len(data) - 1
range = "%s%d:%s%d" % (start_letter, start_row, end_letter, end_row)
print "Range is: " + range
cell_list = wks.range(range)
try:
for i, val in enumerate(data): #gives us a tuple of an index and value
cell_list[i].value = val #use the index on cell_list and the val from cell_values
#Update the whole sheet
wks.update_cells(cell_list)
except:
print "Exception"
this_data_ex = [['data1', 'data1'], ['data2', 'data2']]
write_spreadsheet('python-test', 1, this_data_ex, 1)
This works, but it does not separate the list row entries into the correct columns. 这可行,但不会将列表行条目分成正确的列。 Output on Google sheets looks like this:
Google表格上的输出如下所示:
A B
['data1', 'data1'] ['data2', 'data2'] ['data1','data1'] ['data2','data2']
How can I fix the "try - for" section to write each data entry to a new cell, then wrap the row at the correct place? 如何修复“ try-for”部分,将每个数据条目写入新的单元格,然后将行包装在正确的位置? (like this)
(像这样)
A | B
data1 | data1 | data1
数据1
data2 | 数据2 | data2
数据2
A Double nested for loop; Double嵌套的for循环; one for the rows, one for the columns, then update each cell individually.
一个用于行,一个用于列,然后分别更新每个单元格。 This section seemed to work properly with the desired outcome:
本节似乎可以正常工作并达到预期的结果:
try:
idx = 0
for (start_row, rowlist) in enumerate(data):
for (colnum, value) in enumerate(rowlist):
cell_list[idx].value = value
idx += 1
if idx >= len(cell_list):
break
# Update the whole sheet
wks.update_cells(cell_list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.