我有一个数据列表(从CSV中提取),我正在尝试使用Python / GSpread更新Google Doc上的一系列单元格。这是我的代码示例:
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)
这样可行,但它不会将列表行条目分隔为正确的列。 Google表格上的输出如下所示:
A B
['data1','data1'] ['data2','data2']
如何修复“try-for”部分将每个数据条目写入新单元格,然后将行包装在正确的位置? (像这样)
A | B
data1 | DATA1
data2 | data2
答案 0 :(得分:1)
双嵌套for循环;一个用于行,一个用于列,然后单独更新每个单元。这部分似乎与期望的结果一起正常工作:
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)